A production-ready email generation system that produces professional, contextually-appropriate emails using advanced LLM prompt engineering. Includes comprehensive evaluation metrics for measuring email quality.
- Email Generation: Build an assistant that generates professional emails from Intent, Facts, and Tone
- Custom Metrics: Implement 3 custom evaluation metrics tailored to email quality assessment
- Model Comparison: Compare two prompting strategies (Advanced vs. Baseline) using the same metrics
- β Working email generation assistant with advanced prompt engineering
- β 3 custom evaluation metrics with LLM-as-Judge evaluation
- β 10 test scenarios with reference emails
- β Structured evaluation results (JSON, CSV)
- β Comparative analysis report
- β Complete code repository with documentation
email-generation-assistant/
βββ src/
β βββ email_generator.py # Email generation with 2 strategies
β βββ evaluator.py # Main evaluation orchestrator
β βββ config.py # Configuration management
βββ data/
β βββ test_scenarios.py # 10 test scenarios with reference emails
βββ metrics/
β βββ evaluation_metrics.py # 3 custom metrics implementation
βββ output/
β βββ evaluation_results.json # Raw evaluation data
β βββ evaluation_summary.csv # Metric scores in CSV format
β βββ analysis_report.md # Comparative analysis
β βββ METRICS_DOCUMENTATION.md # Metric definitions
βββ requirements.txt
βββ .env.example
βββ README.md
# Clone repository
git clone <repo-url>
cd email-generation-assistant
# Install dependencies
pip install -r requirements.txt
# Configure API keys
cp .env.example .env
# Edit .env with your API keys:
# OPENAI_API_KEY=your_key_here
# GEMINI_API_KEY=your_key_here (optional)# Full evaluation with all 10 scenarios
python3 src/evaluator.py --api openai
# Using Gemini API
python3 src/evaluator.py --api geminiResults are automatically generated in output/:
evaluation_results.json- Complete raw scoresevaluation_summary.csv- Summary tableanalysis_report.md- Model comparison analysisMETRICS_DOCUMENTATION.md- Metric definitions
Purpose: Measure how well required facts are included and naturally integrated
Sub-components:
- Fact Coverage: Are all key facts present? (0-100)
- Natural Integration: Do facts flow naturally or are they forced? (0-100)
- Specificity: Is the detail level appropriate? (0-100)
Evaluation: LLM-as-Judge assesses each component, returns average score
Purpose: Evaluate if the email matches the specified tone
Sub-components:
- Tone Match: Does overall tone match specified style? (0-100)
- Vocabulary Appropriateness: Are word choices appropriate? (0-100)
- Emotional Resonance: Does it evoke the right emotional response? (0-100)
Evaluation: LLM-as-Judge calibrated against reference emails
Purpose: Measure clarity, structure, and likelihood to achieve goal
Sub-components:
- Clarity & Structure: Is the email well-organized? (0-100)
- Actionability: Is there a clear call-to-action? (0-100)
- Professional Quality: Free of errors and professional? (0-100)
Evaluation: LLM-as-Judge assesses business communication effectiveness
Overall Score: (Metric1 + Metric2 + Metric3) / 3 = 0-100
Combines three advanced techniques:
- Role-Playing: Position generator as expert professional
- Few-Shot Examples: Show 2 example input-output pairs
- Chain-of-Thought: Request step-by-step reasoning
Result: Higher quality, more consistent outputs
Basic prompt without advanced techniques - serves as baseline for comparison
Result: Faster generation but lower quality
Each scenario includes Intent, Facts, Tone, and Reference Email:
- Follow up after client consultation (professional & warm)
- Request urgent action on stalled project (urgent & direct)
- Congratulate colleague on promotion (genuine & encouraging)
- Request proposal and pricing (formal & business-like)
- Apologize for missed deadline (apologetic & solution-focused)
- Introduce new team member (informative & welcoming)
- Request budget approval for tools (persuasive & data-driven)
- Follow up after job interview (professional & enthusiastic)
- Decline partnership offer (respectful & diplomatic)
- Request project status update (concerned & analytical)
Complete evaluation data for all 20 results (10 scenarios Γ 2 strategies)
[
{
"scenario_id": 1,
"strategy": "A",
"intent": "Follow up after...",
"metric_1_fact_incorporation": 87.5,
"metric_2_tone_consistency": 91.2,
"metric_3_clarity_effectiveness": 89.3,
"average_score": 89.33
}
]Tabular format for easy analysis
scenario_id,strategy,metric_1,metric_2,metric_3,average_score
1,A,87.5,91.2,89.3,89.33
1,B,72.1,75.8,71.2,73.03
...
Comparative analysis with key findings and recommendations
Complete metric definitions and evaluation methodology
OPENAI_API_KEY=sk-...
- Model: gpt-3.5-turbo
- Used for both generation and evaluation
GEMINI_API_KEY=AIza...
- Model: gemini-pro
- Requires API key with Generative AI enabled
Run evaluation to get comparison:
python3 src/evaluator.py --api openaiGenerates analysis showing:
- β Strategy A vs Strategy B performance
- β Metric-by-metric breakdown
- β Failure mode analysis
- β Production recommendation
The evaluation framework shows:
- Strategy A (Advanced): Consistently higher scores across all metrics
- Strategy B (Simple): Baseline comparison, useful for cost/speed tradeoff
- Best Metric: Varies by language model and scenario
- Production Recommendation: Strategy A for quality, Strategy B for speed
system_prompt = f"""
You are an expert professional email ghostwriter with 15+ years of experience.
[Few-Shot Examples showing 2 examples]
INSTRUCTIONS:
Think step-by-step following Chain-of-Thought:
1. Identify core message and desired action
2. Determine best email structure
3. Select vocabulary matching tone
4. Integrate all facts seamlessly
5. Review for clarity and consistency
Generate email for:
Intent: {intent}
Facts: {facts}
Tone: {tone}
"""- Python 3.9+
- LLM APIs: OpenAI (GPT-3.5-turbo), Google Gemini
- Libraries:
openai- OpenAI API clientgoogle-generativeai- Gemini API clientpython-dotenv- Environment configurationpandas- Data analysistextblob- Text analysis
See requirements.txt for complete list:
openai==1.3.0
google-generativeai>=0.4.0
python-dotenv==1.0.0
pandas==2.0.3
textblob==0.17.1
nltk==3.8.1
requests==2.31.0
# 1. Setup
pip install -r requirements.txt
cp .env.example .env # Add API keys
# 2. Run evaluation
python3 src/evaluator.py --api openai
# 3. Check results
cat output/analysis_report.md
cat output/evaluation_summary.csv
# 4. Review detailed metrics
cat output/METRICS_DOCUMENTATION.mdAll outputs are in structured, production-ready formats:
- JSON: For programmatic analysis and integration
- CSV: For spreadsheet analysis and visualization
- Markdown: For human-readable reports and documentation
- Working email generation assistant
- 3 custom metrics with clear definitions
- 10 test scenarios with reference emails
- Structured evaluation results
- Model comparison analysis
- Advanced prompt engineering (Role-Playing + Few-Shot + CoT)
- LLM-as-Judge evaluation methodology
- Production-ready code
- Complete documentation
output/METRICS_DOCUMENTATION.md- Detailed metric explanationsoutput/analysis_report.md- Comparative analysis resultssrc/email_generator.py- Generation implementationmetrics/evaluation_metrics.py- Metric implementationdata/test_scenarios.py- Test data
Core Implementation:
src/email_generator.py- Email generation with Strategy A & Bsrc/evaluator.py- Evaluation orchestratormetrics/evaluation_metrics.py- Custom metrics (all 3)data/test_scenarios.py- 10 test scenarios
Configuration & Data:
requirements.txt- Python dependencies.env.example- API key templateoutput/- Evaluation results
For issues or questions:
- Check
output/METRICS_DOCUMENTATION.mdfor metric details - Review
output/analysis_report.mdfor results interpretation - See
src/evaluator.pyfor execution details
Project Status: β Complete and Production-Ready βββ .env.example # Template for environment variables βββ README.md # This file
## Setup Instructions
### 1. Install Dependencies
```bash
cd "/Users/apple/Desktop/chat assistant"
pip install -r requirements.txt
# Copy the example file
cp .env.example .env
# Edit .env and add your OpenAI API key
# OPENAI_API_KEY=sk-...python src/evaluator.pyThis will:
- Generate emails for all 10 scenarios using Strategy A (advanced prompting)
- Generate emails for all 10 scenarios using Strategy B (simple prompting)
- Evaluate each email against the three custom metrics
- Output results to CSV, JSON, and markdown report files
- Follow up after client consultation
- Request urgent action on stalled project
- Congratulate colleague on promotion
- Request proposal and pricing information
- Apologize for missed deadline with remediation plan
- Introduce new team member to stakeholders
- Request budget approval for software tools
- Follow up on job interview
- Professionally decline partnership offer
- Request detailed project status and risk assessment
After running the evaluation, you'll find:
evaluation_results_YYYYMMDD_HHMMSS.json- Full results with generated emailsevaluation_summary_YYYYMMDD_HHMMSS.csv- Metrics summary (easy for analysis)analysis_report_YYYYMMDD_HHMMSS.md- Comparative analysis and recommendationsMETRICS_DOCUMENTATION.md- Detailed explanation of the three metrics
The email generator implements three advanced techniques:
1. Role-Playing
"You are an expert professional email ghostwriter with 15+ years of experience..."
2. Few-Shot Examples Shows the model example inputs and outputs to guide generation
3. Chain-of-Thought
"Think through this step-by-step:
1. Identify the core message
2. Determine the best structure
3. Select appropriate vocabulary
4. Ensure all facts are included
5. Review for clarity and tone"
Each metric uses LLM-as-a-Judge to provide nuanced evaluation:
- Not just simple keyword matching
- Considers natural integration and contextual appropriateness
- Compares against human-written reference emails
- Evaluates sub-components to provide detailed feedback
Edit data/test_scenarios.py and add new scenarios to the TEST_SCENARIOS list.
Edit src/email_generator.py and update the model parameter:
generator = EmailGenerator(model="gpt-4") # Use different modelModify the criteria in metrics/evaluation_metrics.py to focus on different aspects of email quality.
from src.email_generator import generate_email
# Strategy A: Advanced prompting
email = generate_email(
intent="Follow up after design review meeting",
facts=[
"Discussed new dashboard mockups",
"Team agreed on implementation timeline of 3 weeks",
"Budget approved for contractors"
],
tone="professional and collaborative",
strategy="A"
)
print(email)- Fact Incorporation: Ensures the assistant remembers and includes all requirements
- Tone Consistency: Validates that email matches the intended communication style
- Clarity & Effectiveness: Confirms emails will achieve their business goals
- Strategy A (Advanced): Shows the power of well-engineered prompts
- Strategy B (Simple): Provides a baseline to demonstrate improvements
- More nuanced than keyword matching or simple heuristics
- Can evaluate semantic appropriateness, not just surface features
- Handles the subjective nature of email quality assessment
- Generate: Create emails for each scenario with both strategies
- Evaluate: Score each email against three metrics
- Compare: Analyze differences between strategies
- Recommend: Identify best approach for production use
- Each metric scored 0-100
- Sub-components averaged together
- Overall score = (Metric1 + Metric2 + Metric3) / 3
- Higher scores indicate better performance
- Strategy A typically outperforms Strategy B by 10-20 points
- Best improvements in Metric 2 (Tone Consistency) and Metric 3 (Clarity)
- Strategy A more consistent across different scenarios
- Check
analysis_report_*.mdfor summary findings - Review
evaluation_summary_*.csvfor scenario-level performance - Study generated emails in
evaluation_results_*.jsonfor qualitative feedback - Focus on low-scoring scenarios to understand failure modes
Error: OpenAI API key not found
Solution: Check .env file has OPENAI_API_KEY set correctly
Error: Rate limit exceeded
Solution: Add delays between requests or use a higher API tier
Error: Model 'gpt-4' not found
Solution: Ensure you have access to that model or use 'gpt-3.5-turbo'
- Python 3.8+
- OpenAI API key (with available credits)
- ~5-10 minutes runtime for full evaluation
- ~100 API calls total (generates + evaluates 20 emails)
This project is provided as-is for educational and demonstration purposes.
Review the comments in the source code for detailed explanations of implementation decisions.