Spaces:
Sleeping
Sleeping
Piers Lyon
Claude Opus 4.6 (1M context)
Include all modified source files missing from initial deploy
9c6926e Download email_engine.py from mipwr-admin/curium-intel: direct link, hf CLI and curl.
- Browser
- Download file 38.5 kB
-
https://huggingface.co/spaces/mipwr-admin/curium-intel/resolve/main/email_engine.py
- Command line
-
hf download hf://spaces/mipwr-admin/curium-intel/email_engine.py
-
curl -L -o email_engine.py https://huggingface.co/spaces/mipwr-admin/curium-intel/resolve/main/email_engine.py
38.5 kB
"""
Email Engine Module (email_engine.py)
Handles email drafting and sending for Curium Lead Intelligence Platform.
Enhanced with:
- Curium-specific positioning and values
- Service-line targeted outreach
- LinkedIn message drafting (< 300 chars)
- CODE 3i specific outreach
"""
import os
import json
from pathlib import Path
from datetime import datetime
from dataclasses import dataclass
from typing import Optional
from dotenv import load_dotenv
from anthropic import Anthropic
# Load environment variables
env_path = Path(__file__).parent / '.env'
load_dotenv(dotenv_path=env_path, override=True)
# Initialize Anthropic client
_client = None
def get_client():
"""Get or create the Anthropic client."""
global _client
if _client is None:
api_key = os.environ.get("ANTHROPIC_API_KEY")
if not api_key:
raise ValueError("ANTHROPIC_API_KEY not set")
_client = Anthropic(api_key=api_key)
return _client
@dataclass
class EmailDraft:
"""Represents a drafted email ready for review."""
from_name: str
to_name: str
to_company: str
to_position: str
subject: str
body: str
draft_type: str # "warm_intro", "mover_outreach", "service_specific", "code_3i", "linkedin", "general"
confidence: int
notes: str
created_at: datetime
lead_id: Optional[int] = None
contact_email: Optional[str] = None
status: str = "draft"
service_line: Optional[str] = None # "transformation_delivery", "culture_capability", "both"
recommended_services: Optional[list] = None # List of service IDs
linkedin_version: Optional[str] = None # < 300 char LinkedIn connection request
# ============================================================================
# CURIUM GHOSTWRITER SYSTEM PROMPT
# ============================================================================
GHOSTWRITER_SYSTEM_PROMPT = """You are writing casual, professional emails on behalf of consultants at **Curium Solutions**, a UK & Ireland transformation consultancy.
**About Curium:**
- Two practice areas: Transformation Delivery (programme management, change, M&A integration) and Culture & Capability (coaching, leadership, team development)
- Entry point service: **Change Launchpad** β low-risk 3-4 week diagnostic that maps transformation readiness, identifies blockers, and builds momentum from Day One. This is the recommended starting conversation for all new prospects.
- Proprietary product: CODE 3i β digital team assessment used by DAC Beachcroft, Canada Life, 100+ orgs
- Blue-chip client base: Rolls-Royce, NASA, Bentley, Headlam, DAC Beachcroft, Canada Life
- Values: People First, Keep It Simple, Make It Real
- NPS: 83
- Tone: Warm, practical, no-nonsense. We're doers, not deck-builders.
**Style Guidelines:**
- British English spelling and tone
- Warm but professional β not overly formal or stiff
- Brief and to the point (3-4 short paragraphs max)
- Natural, conversational language
- No corporate jargon or buzzwords
- Genuine interest in the person, not pushy sales
- Reference Curium naturally when relevant (never forced)
- When positioning entry point: "We've developed something called Change Launchpad β it's a 3-4 week diagnostic that maps exactly where you need support. Most clients start there."
- When mentioning CODE: "Our CODE assessment has been brilliant for teams going through exactly this kind of change"
- When mentioning transformation delivery: "We've been embedding senior programme people into similar situations β Rolls-Royce, Bentley, NASA among others"
- When mentioning culture work: "We've been doing some really interesting culture work with organisations going through similar changes β Headlam said it had a real ripple effect across the organisation"
**Structure:**
1. Opening: Acknowledge the connection/how you know them
2. Middle: Note something relevant (job move, company news, signal, etc.)
3. Soft bridge: Casually mention how Curium might be relevant
4. Close: Low-pressure, friendly sign-off
**Also generate a linkedin_version:** A LinkedIn connection request message under 300 characters. Friendly, specific to the person, with a hook.
**Output Format:**
Return JSON only:
{
"subject": "Subject line here",
"body": "Email body here with \\n for line breaks",
"linkedin_version": "Short LinkedIn connection request under 300 chars",
"confidence": 85,
"notes": "Brief explanation of approach taken"
}"""
def _match_persona(contact_position: str) -> Optional[dict]:
"""Match a contact's position to a buyer persona from config.yaml.
Returns persona dict with title_pattern, service_affinity, priority,
or None if no match found.
"""
if not contact_position:
return None
try:
import yaml
with open('config.yaml', 'r') as f:
config = yaml.safe_load(f)
personas = config.get('target_personas', [])
except Exception:
return None
pos_lower = contact_position.lower()
best_match = None
best_score = 0
for persona in personas:
pattern = persona.get('title_pattern', '').lower()
if not pattern:
continue
# Check for substring match or keyword overlap
if pattern in pos_lower or pos_lower in pattern:
score = 100
else:
# Word overlap scoring
pattern_words = set(pattern.split())
pos_words = set(pos_lower.split())
overlap = pattern_words & pos_words
score = (len(overlap) / max(len(pattern_words), 1)) * 80
if score > best_score and score >= 40:
best_score = score
best_match = persona
return best_match
def _build_persona_context(contact_position: str) -> str:
"""Build persona-aware context string for email prompts."""
persona = _match_persona(contact_position)
if not persona:
return ""
affinities = persona.get('service_affinity', [])
priority = persona.get('priority', 'medium')
service_labels = {
'transformation_delivery': 'Transformation Delivery (programme management, change, M&A)',
'culture_capability': 'Culture & Capability (coaching, leadership, team development)',
'code_3i': 'CODE 3i (digital team assessment)',
}
affinity_str = ', '.join(service_labels.get(a, a) for a in affinities)
return (
f"\n**Buyer Persona Insight ({priority} priority):**\n"
f"- This persona ({persona['title_pattern']}) typically buys: {affinity_str}\n"
f"- Tailor the message to their likely pain points and decision-making authority\n"
f"- {'This is a high-priority persona β be specific about relevant services' if priority == 'high' else 'Position services naturally without being pushy'}\n"
)
def draft_warm_intro_email(
colleague_name: str,
contact_name: str,
contact_company: str,
contact_position: str,
is_mover: bool = False,
previous_company: Optional[str] = None,
additional_context: Optional[str] = None
) -> EmailDraft:
"""
Draft a ghostwritten warm intro email using Claude.
Now includes Curium positioning and LinkedIn version.
"""
if is_mover and previous_company:
scenario = f"""
Write a casual email from {colleague_name} to {contact_name}.
Context:
- {colleague_name} and {contact_name} are LinkedIn connections
- {contact_name} recently moved from {previous_company} to {contact_company}
- {contact_name}'s new role is: {contact_position}
- {colleague_name} noticed this move and wants to reconnect
Goal:
- Congratulate them on the new role
- Mention {colleague_name}'s colleague Piers at Curium is doing interesting work in their sector
- Soft suggestion: "might be worth a chat" or similar low-pressure ask
- Keep it warm and genuine, not salesy
"""
else:
scenario = f"""
Write a casual email from {colleague_name} to {contact_name}.
Context:
- {colleague_name} and {contact_name} are LinkedIn connections
- {contact_name} works at {contact_company} as {contact_position}
- {colleague_name} wants to reconnect and mention some relevant work
Goal:
- Reference the LinkedIn connection naturally
- Mention {colleague_name}'s colleague Piers at Curium is doing some work in their sector
- Soft suggestion: "might be worth a chat" or similar low-pressure ask
- Keep it warm and genuine, not salesy
"""
if additional_context:
scenario += f"\nAdditional context: {additional_context}"
# Inject buyer persona insight if available
persona_ctx = _build_persona_context(contact_position)
if persona_ctx:
scenario += persona_ctx
try:
client = get_client()
response = client.messages.create(
model="claude-sonnet-4-20250514",
max_tokens=1024,
system=GHOSTWRITER_SYSTEM_PROMPT,
messages=[{"role": "user", "content": scenario}]
)
response_text = response.content[0].text.strip()
# Clean up markdown code blocks if present
if response_text.startswith("```"):
lines = response_text.split('\n')
if lines[0].startswith("```"):
lines = lines[1:]
if lines and lines[-1].strip() == "```":
lines = lines[:-1]
response_text = '\n'.join(lines).strip()
try:
result = json.loads(response_text)
return EmailDraft(
from_name=colleague_name,
to_name=contact_name,
to_company=contact_company,
to_position=contact_position,
subject=result.get("subject", f"Quick hello from {colleague_name}"),
body=result.get("body", "").replace("\\n", "\n"),
draft_type="mover_outreach" if is_mover else "warm_intro",
confidence=int(result.get("confidence", 70)),
notes=result.get("notes", ""),
created_at=datetime.now(),
status="draft",
linkedin_version=result.get("linkedin_version", "")[:300] if result.get("linkedin_version") else None,
)
except json.JSONDecodeError:
return EmailDraft(
from_name=colleague_name,
to_name=contact_name,
to_company=contact_company,
to_position=contact_position,
subject=f"Quick hello from {colleague_name}",
body=response_text,
draft_type="mover_outreach" if is_mover else "warm_intro",
confidence=50,
notes="Warning: AI response was not in expected format",
created_at=datetime.now(),
status="draft"
)
except Exception as e:
return EmailDraft(
from_name=colleague_name,
to_name=contact_name,
to_company=contact_company,
to_position=contact_position,
subject="(Draft failed)",
body=f"Error generating draft: {str(e)}",
draft_type="error",
confidence=0,
notes=str(e),
created_at=datetime.now(),
status="failed"
)
def draft_service_specific_email(
colleague_name: str,
contact_name: str,
contact_company: str,
contact_position: str,
service_line: str,
signal_type: str = "",
signal_context: str = "",
) -> EmailDraft:
"""Draft a targeted outreach email based on specific Curium service line and signal.
Args:
service_line: 'transformation_delivery' or 'culture_capability'
signal_type: e.g. 'restructuring', 'leadership_change', 'culture_crisis'
signal_context: Additional context about the signal (news headline, etc.)
"""
service_desc = {
'transformation_delivery': "transformation delivery β programme management, change management, M&A integration",
'culture_capability': "culture and capability work β leadership development, coaching, team profiling with CODE",
}
scenario = f"""
Write a casual outreach email from {colleague_name} to {contact_name} at {contact_company}.
{colleague_name} is a Curium colleague who already has a LinkedIn connection with {contact_name} β they should reach out directly as themselves, not introduce someone else.
Context:
- {contact_name} is {contact_position} at {contact_company}
- We've identified a signal: {signal_type} β {signal_context}
- The relevant Curium service area is: {service_desc.get(service_line, service_line)}
Goal:
- This is {colleague_name} reaching out to their own connection β keep it personal and natural
- Reference the signal naturally (don't say "we spotted a signal" β instead reference the news/change)
- Position Curium's relevant expertise casually as something {colleague_name}'s team does
- If culture/capability: mention CODE 3i naturally ("Our CODE assessment has been brilliant for teams going through...")
- If transformation delivery: mention track record ("We've been embedding senior programme people into similar situations")
- End with a soft ask for a conversation
- Keep it under 4 paragraphs
"""
# Inject buyer persona insight if available
persona_ctx = _build_persona_context(contact_position)
if persona_ctx:
scenario += persona_ctx
try:
client = get_client()
response = client.messages.create(
model="claude-sonnet-4-20250514",
max_tokens=1024,
system=GHOSTWRITER_SYSTEM_PROMPT,
messages=[{"role": "user", "content": scenario}]
)
response_text = response.content[0].text.strip()
if response_text.startswith("```"):
lines = response_text.split('\n')
if lines[0].startswith("```"):
lines = lines[1:]
if lines and lines[-1].strip() == "```":
lines = lines[:-1]
response_text = '\n'.join(lines).strip()
try:
result = json.loads(response_text)
return EmailDraft(
from_name=colleague_name,
to_name=contact_name,
to_company=contact_company,
to_position=contact_position,
subject=result.get("subject", f"Quick thought for {contact_company}"),
body=result.get("body", "").replace("\\n", "\n"),
draft_type="service_specific",
confidence=int(result.get("confidence", 70)),
notes=result.get("notes", ""),
created_at=datetime.now(),
status="draft",
service_line=service_line,
linkedin_version=result.get("linkedin_version", "")[:300] if result.get("linkedin_version") else None,
)
except json.JSONDecodeError:
return EmailDraft(
from_name=colleague_name, to_name=contact_name,
to_company=contact_company, to_position=contact_position,
subject=f"Quick thought for {contact_company}",
body=response_text, draft_type="service_specific",
confidence=50, notes="JSON parse error",
created_at=datetime.now(), status="draft",
service_line=service_line,
)
except Exception as e:
return EmailDraft(
from_name=colleague_name, to_name=contact_name,
to_company=contact_company, to_position=contact_position,
subject="(Draft failed)", body=f"Error: {str(e)}",
draft_type="error", confidence=0, notes=str(e),
created_at=datetime.now(), status="failed",
)
def draft_linkedin_message(
contact_name: str,
contact_company: str,
contact_position: str,
message_type: str = "connection",
context: str = "",
) -> str:
"""Draft a short LinkedIn message (< 300 chars for connection requests).
Args:
message_type: 'connection', 'inmail', 'comment', 'follow_up'
context: Additional context
Returns:
String message ready for LinkedIn
"""
char_limits = {
'connection': 300,
'inmail': 1900,
'comment': 1250,
'follow_up': 300,
}
limit = char_limits.get(message_type, 300)
persona_ctx = _build_persona_context(contact_position)
prompt = f"""Write a {message_type} LinkedIn message to {contact_name} ({contact_position} at {contact_company}).
Context: {context if context else 'General professional outreach'}
{persona_ctx}
Rules:
- Maximum {limit} characters
- Warm, professional, British English
- Reference something specific about them or their company
- If connection request: mention a shared interest or why you'd like to connect
- No corporate jargon
- From a Curium Solutions consultant
Return ONLY the message text, no JSON, no quotes."""
try:
client = get_client()
response = client.messages.create(
model="claude-sonnet-4-20250514",
max_tokens=256,
system=GHOSTWRITER_SYSTEM_PROMPT,
messages=[{"role": "user", "content": prompt}]
)
text = response.content[0].text.strip()
return text[:limit]
except Exception as e:
return f"Hi {contact_name.split()[0] if contact_name else 'there'}, I'd love to connect β working on some interesting transformation projects that might be relevant to {contact_company}."[:limit]
def draft_code_3i_outreach(
colleague_name: str,
contact_name: str,
contact_company: str,
contact_position: str,
trigger: str = "",
) -> EmailDraft:
"""Draft a CODE 3i specific positioning email."""
scenario = f"""
Write a casual email from {colleague_name} to {contact_name} at {contact_company} specifically about CODE 3i.
Context:
- {contact_name} is {contact_position} at {contact_company}
- Signal/trigger: {trigger if trigger else 'General interest in team effectiveness'}
About CODE 3i:
- Digital team assessment, takes 10 minutes per person
- Gives instant insight into team dynamics, communication styles, decision-making
- Used by DAC Beachcroft, Canada Life, and 100+ organisations
- Perfect for: new teams, teams under pressure, post-merger integration, hybrid working
- Visual, intuitive output β no psychology degree needed
- Runs at scale across global teams
Goal:
- Make CODE 3i sound practical and easy, not salesy
- Use phrases like "our CODE assessment has been brilliant for..." or "we've been getting great results with..."
- Reference the trigger/signal naturally
- End with soft ask: quick demo or chat
- Under 4 paragraphs
"""
# Inject buyer persona insight if available
persona_ctx = _build_persona_context(contact_position)
if persona_ctx:
scenario += persona_ctx
try:
client = get_client()
response = client.messages.create(
model="claude-sonnet-4-20250514",
max_tokens=1024,
system=GHOSTWRITER_SYSTEM_PROMPT,
messages=[{"role": "user", "content": scenario}]
)
response_text = response.content[0].text.strip()
if response_text.startswith("```"):
lines = response_text.split('\n')
if lines[0].startswith("```"):
lines = lines[1:]
if lines and lines[-1].strip() == "```":
lines = lines[:-1]
response_text = '\n'.join(lines).strip()
try:
result = json.loads(response_text)
return EmailDraft(
from_name=colleague_name,
to_name=contact_name,
to_company=contact_company,
to_position=contact_position,
subject=result.get("subject", f"Quick thought on team effectiveness at {contact_company}"),
body=result.get("body", "").replace("\\n", "\n"),
draft_type="code_3i",
confidence=int(result.get("confidence", 70)),
notes=result.get("notes", ""),
created_at=datetime.now(),
status="draft",
service_line="culture_capability",
recommended_services=["code_3i", "team_profiling"],
linkedin_version=result.get("linkedin_version", "")[:300] if result.get("linkedin_version") else None,
)
except json.JSONDecodeError:
return EmailDraft(
from_name=colleague_name, to_name=contact_name,
to_company=contact_company, to_position=contact_position,
subject=f"Quick thought on team effectiveness at {contact_company}",
body=response_text, draft_type="code_3i",
confidence=50, notes="JSON parse error",
created_at=datetime.now(), status="draft",
service_line="culture_capability",
recommended_services=["code_3i", "team_profiling"],
)
except Exception as e:
return EmailDraft(
from_name=colleague_name, to_name=contact_name,
to_company=contact_company, to_position=contact_position,
subject="(Draft failed)", body=f"Error: {str(e)}",
draft_type="error", confidence=0, notes=str(e),
created_at=datetime.now(), status="failed",
)
def draft_change_launchpad_outreach(
colleague_name: str,
contact_name: str,
contact_company: str,
contact_position: str,
trigger: str = "",
) -> EmailDraft:
"""Draft a Change Launchpad entry conversation email."""
scenario = f"""
Write a casual email from {colleague_name} to {contact_name} at {contact_company} specifically about Change Launchpad.
Context:
- {contact_name} is {contact_position} at {contact_company}
- Signal/trigger: {trigger if trigger else 'Visible transformation activity'}
About Change Launchpad:
- Low-risk, low-cost diagnostic that maps transformation readiness
- Identifies exactly where external support would help β and where it wouldn't
- Used by Rolls-Royce, NASA, Bentley, Headlam and others
- 3-4 week engagement, practical output (roadmap, quick wins, governance model)
- Entry point to deeper transformation work β not just a diagnostic, it builds momentum from Day One
- Three phases: Engage (align the team behind a shared vision), Assess (identify blockers), Shape (provide a clear way forward)
Goal:
- Position Change Launchpad as a diagnostic conversation, not a sales pitch
- Make it sound practical and essential β "most organisations going through change start here"
- Use phrases like "Change Launchpad has been brilliant for..." or "We've been getting great results with..."
- Reference the trigger/signal naturally
- End with soft ask: chat about transformation readiness
- Under 4 paragraphs
"""
# Inject buyer persona insight if available
persona_ctx = _build_persona_context(contact_position)
if persona_ctx:
scenario += persona_ctx
try:
client = get_client()
response = client.messages.create(
model="claude-sonnet-4-20250514",
max_tokens=1024,
system=GHOSTWRITER_SYSTEM_PROMPT,
messages=[{"role": "user", "content": scenario}]
)
response_text = response.content[0].text.strip()
if response_text.startswith("```"):
lines = response_text.split('\n')
if lines[0].startswith("```"):
lines = lines[1:]
if lines and lines[-1].strip() == "```":
lines = lines[:-1]
response_text = '\n'.join(lines).strip()
try:
result = json.loads(response_text)
return EmailDraft(
from_name=colleague_name,
to_name=contact_name,
to_company=contact_company,
to_position=contact_position,
subject=result.get("subject", f"Quick thought on transformation readiness at {contact_company}"),
body=result.get("body", "").replace("\\n", "\n"),
draft_type="change_launchpad",
confidence=int(result.get("confidence", 75)),
notes=result.get("notes", ""),
created_at=datetime.now(),
status="draft",
service_line="both",
recommended_services=["change_management", "culture_diagnostics"],
linkedin_version=result.get("linkedin_version", "")[:300] if result.get("linkedin_version") else None,
)
except json.JSONDecodeError:
return EmailDraft(
from_name=colleague_name, to_name=contact_name,
to_company=contact_company, to_position=contact_position,
subject=f"Quick thought on transformation readiness at {contact_company}",
body=response_text, draft_type="change_launchpad",
confidence=50, notes="JSON parse error",
created_at=datetime.now(), status="draft",
service_line="both",
recommended_services=["change_management", "culture_diagnostics"],
)
except Exception as e:
return EmailDraft(
from_name=colleague_name, to_name=contact_name,
to_company=contact_company, to_position=contact_position,
subject="(Draft failed)", body=f"Error: {str(e)}",
draft_type="error", confidence=0, notes=str(e),
created_at=datetime.now(), status="failed",
)
def draft_email_for_network_hit(network_hit: dict, lead_info: Optional[dict] = None) -> EmailDraft:
"""Convenience function to draft an email given a network hit result."""
return draft_warm_intro_email(
colleague_name=network_hit.get('colleague_owner', 'Your colleague'),
contact_name=network_hit.get('contact_name', 'Contact'),
contact_company=network_hit.get('company', 'their company'),
contact_position=network_hit.get('position', 'their role'),
is_mover=network_hit.get('is_new_company', False),
previous_company=network_hit.get('previous_company'),
additional_context=json.dumps(lead_info) if lead_info else None
)
# ============================================================================
# EMAIL SENDING (DISABLED/MOCKED FOR NOW)
# ============================================================================
SENDING_ENABLED = False
def send_email(draft: EmailDraft, to_email: str) -> dict:
"""Send an email based on a draft. CURRENTLY MOCKED."""
if not SENDING_ENABLED:
return {
"success": False,
"status": "mocked",
"message": "Email sending is currently disabled. Draft saved for manual sending.",
"draft": draft,
"would_send_to": to_email
}
return {
"success": False,
"status": "not_implemented",
"message": "SMTP sending not yet implemented"
}
def enable_sending():
"""Enable email sending (future use - requires SMTP config)."""
global SENDING_ENABLED
smtp_user = os.environ.get("SMTP_USERNAME")
smtp_pass = os.environ.get("SMTP_PASSWORD")
if not smtp_user or not smtp_pass:
raise ValueError("SMTP credentials not configured in .env")
SENDING_ENABLED = True
return True
def disable_sending():
"""Disable email sending."""
global SENDING_ENABLED
SENDING_ENABLED = False
return True
# ============================================================================
# UTILITY FUNCTIONS
# ============================================================================
def format_draft_for_display(draft: EmailDraft) -> str:
"""Format a draft for text display."""
service_info = ""
if draft.service_line:
service_info = f"\nService Line: {draft.service_line}"
if draft.recommended_services:
service_info += f"\nServices: {', '.join(draft.recommended_services)}"
linkedin_info = ""
if draft.linkedin_version:
linkedin_info = f"\n\n--- LinkedIn Version ({len(draft.linkedin_version)} chars) ---\n{draft.linkedin_version}"
return f"""
βββββββββββββββββββββββββββββββββββββββββββββββ
EMAIL DRAFT ({draft.draft_type.upper()})
βββββββββββββββββββββββββββββββββββββββββββββββ
From: {draft.from_name}
To: {draft.to_name} ({draft.to_position} at {draft.to_company})
Subject: {draft.subject}{service_info}
βββββββββββββββββββββββββββββββββββββββββββββββ
{draft.body}
βββββββββββββββββββββββββββββββββββββββββββββββ
Confidence: {draft.confidence}%
Notes: {draft.notes}
Status: {draft.status}
Created: {draft.created_at.strftime('%Y-%m-%d %H:%M')}{linkedin_info}
βββββββββββββββββββββββββββββββββββββββββββββββ
"""
def get_copyable_email(draft: EmailDraft) -> dict:
"""Get email components ready for clipboard copy."""
result = {
"subject": draft.subject,
"body": draft.body,
"full_text": f"Subject: {draft.subject}\n\n{draft.body}"
}
if draft.linkedin_version:
result["linkedin_version"] = draft.linkedin_version
return result
def draft_colleague_intro_request(
colleague_name: str,
contact_name: str,
contact_title: str,
company_name: str,
company_score: int = 0,
posts_about_transformation: bool = False,
contact_active: bool = False,
connection_degree: str = "?",
) -> dict:
"""Draft a quick internal email asking a colleague to make a LinkedIn intro."""
first_name = contact_name.split()[0] if contact_name else "them"
if posts_about_transformation:
signal_context = (
" β and they're posting about transformation, right in our sweet spot"
)
elif contact_active:
signal_context = " β and they're active on LinkedIn, so timing's good"
else:
signal_context = ""
subject = f"Worth reaching out to {first_name} at {company_name}?"
body = (
f"Hi {colleague_name},\n\n"
f"Hope you're well. I noticed you're connected to {contact_name} "
f"({contact_title}) at {company_name} on LinkedIn.\n\n"
f"{company_name} is showing strong signals right now "
f"(opportunity score: {company_score}){signal_context}.\n\n"
f"Would you be up for dropping them a message? Even a casual "
f"LinkedIn note to reconnect would be great β you've got the "
f"relationship so it'll land much better coming from you.\n\n"
f"Cheers,\nPiers"
)
return {
"subject": subject,
"body": body,
"full_text": f"Subject: {subject}\n\n{body}",
}
def draft_batch_colleague_summary(routes: list) -> dict:
"""Draft a single team email grouping all routes by colleague."""
by_colleague: dict[str, list] = {}
for r in routes:
col = r.get("colleague_name", "Unknown")
by_colleague.setdefault(col, []).append(r)
sections = []
for colleague, entries in by_colleague.items():
lines = [f"{colleague}:"]
for e in entries:
name = e.get("contact_name", "?")
title = e.get("contact_title", "")
company = e.get("company_name", "?")
if e.get("posts_about_transformation"):
signal = "posting about transformation"
elif e.get("contact_active"):
signal = "active on LinkedIn"
else:
signal = f"score {e.get('company_score', 0)}"
lines.append(f" - {name} ({title}) at {company} β {signal}")
sections.append("\n".join(lines))
subject = "LinkedIn routes into our hottest companies β worth a message?"
body = (
"Hi team,\n\n"
"A few of our hottest opportunities have routes via your LinkedIn "
"connections. You've got the relationship, so a message from you "
"would land much better than a cold approach.\n\n"
+ "\n\n".join(sections)
+ "\n\n"
"Even a casual LinkedIn note to reconnect would be great.\n\n"
"Cheers,\nPiers"
)
return {
"subject": subject,
"body": body,
"full_text": f"Subject: {subject}\n\n{body}",
"recipients": set(by_colleague.keys()),
}
# ============================================================================
# FOLLOW-UP EMAIL GENERATION
# ============================================================================
def draft_follow_up_email(
contact_name: str,
contact_company: str,
contact_position: str = "",
original_context: str = "",
follow_up_number: int = 1,
channel: str = "email",
) -> EmailDraft:
"""Generate a follow-up email variation based on the follow-up number.
Args:
contact_name: Name of the person to follow up with
contact_company: Their company
contact_position: Their role
original_context: What the initial outreach was about
follow_up_number: 1 = first follow-up, 2 = second follow-up
channel: "email" or "linkedin"
"""
if follow_up_number == 1:
tone = "gentle nudge, add a new piece of value (article, insight, relevant news)"
else:
tone = "final touch, suggest a specific time/date, or offer to connect them with a relevant colleague instead"
scenario = f"""Write a follow-up {channel} message.
Context:
- This is follow-up #{follow_up_number} to {contact_name} at {contact_company}
- Their role: {contact_position}
- Original outreach was about: {original_context}
- They haven't responded to the previous message
Tone: {tone}
Rules:
- Keep it SHORT (2-3 sentences for LinkedIn, 3-4 sentences for email)
- Reference the original message naturally ("I dropped you a note last week about...")
- Add new value β don't just say "following up"
- No pressure, no guilt-tripping
- British English, warm and practical
"""
try:
client = get_client()
response = client.messages.create(
model="claude-sonnet-4-20250514",
max_tokens=512,
system=GHOSTWRITER_SYSTEM_PROMPT,
messages=[{"role": "user", "content": scenario}]
)
response_text = response.content[0].text.strip()
if response_text.startswith("```"):
lines = response_text.split('\n')
if lines[0].startswith("```"):
lines = lines[1:]
if lines and lines[-1].strip() == "```":
lines = lines[:-1]
response_text = '\n'.join(lines).strip()
try:
result = json.loads(response_text)
subject = result.get("subject", f"Following up - {contact_company}")
body = result.get("body", response_text)
linkedin_version = result.get("linkedin_version", "")
except json.JSONDecodeError:
subject = f"Following up - {contact_company}"
body = response_text
linkedin_version = response_text[:300] if channel == "linkedin" else ""
return EmailDraft(
from_name="Piers",
to_name=contact_name,
to_company=contact_company,
to_position=contact_position,
subject=subject,
body=body,
draft_type="follow_up",
confidence=70,
notes=f"Follow-up #{follow_up_number}",
created_at=datetime.now(),
linkedin_version=linkedin_version,
)
except Exception as e:
return EmailDraft(
from_name="Piers",
to_name=contact_name,
to_company=contact_company,
to_position=contact_position,
subject=f"Following up - {contact_company}",
body=f"Error generating follow-up: {str(e)[:100]}",
draft_type="follow_up",
confidence=0,
notes=f"Generation failed: {str(e)[:50]}",
created_at=datetime.now(),
)
# ============================================================================
# TEST / DEMO
# ============================================================================
if __name__ == "__main__":
print("Testing Email Engine (Curium Enhanced)")
print("=" * 60)
# Test 1: Warm intro for a mover
print("\nTest 1: Mover Outreach Email")
print("-" * 40)
draft = draft_warm_intro_email(
colleague_name="Adam",
contact_name="Sarah Thompson",
contact_company="Unilever",
contact_position="Head of Organisational Development",
is_mover=True,
previous_company="Diageo"
)
print(format_draft_for_display(draft))
# Test 2: Service-specific email
print("\nTest 2: Service-Specific (TD) Email")
print("-" * 40)
draft2 = draft_service_specific_email(
colleague_name="Piers",
contact_name="James Wilson",
contact_company="Barclays",
contact_position="Director of Transformation",
service_line="transformation_delivery",
signal_type="restructuring",
signal_context="Barclays announces major restructuring of retail banking division"
)
print(format_draft_for_display(draft2))
# Test 3: CODE 3i outreach
print("\nTest 3: CODE 3i Outreach")
print("-" * 40)
draft3 = draft_code_3i_outreach(
colleague_name="Stuart",
contact_name="Emma Davies",
contact_company="Lloyds",
contact_position="Head of Leadership Development",
trigger="New team formation after M&A integration"
)
print(format_draft_for_display(draft3))
# Test 4: LinkedIn message
print("\nTest 4: LinkedIn Connection Request")
print("-" * 40)
msg = draft_linkedin_message(
contact_name="Mark Roberts",
contact_company="HSBC",
contact_position="Programme Director",
message_type="connection",
context="HSBC restructuring their technology division"
)
print(f"Message ({len(msg)} chars): {msg}")
"""
Email Engine Module (email_engine.py)
Handles email drafting and sending for Curium Lead Intelligence Platform.
Enhanced with:
- Curium-specific positioning and values
- Service-line targeted outreach
- LinkedIn message drafting (< 300 chars)
- CODE 3i specific outreach
"""
import os
import json
from pathlib import Path
from datetime import datetime
from dataclasses import dataclass
from typing import Optional
from dotenv import load_dotenv
from anthropic import Anthropic
# Load environment variables
env_path = Path(__file__).parent / '.env'
load_dotenv(dotenv_path=env_path, override=True)
# Initialize Anthropic client
_client = None
def get_client():
"""Get or create the Anthropic client."""
global _client
if _client is None:
api_key = os.environ.get("ANTHROPIC_API_KEY")
if not api_key:
raise ValueError("ANTHROPIC_API_KEY not set")
_client = Anthropic(api_key=api_key)
return _client
class EmailDraft:
"""Represents a drafted email ready for review."""
from_name: str
to_name: str
to_company: str
to_position: str
subject: str
body: str
draft_type: str # "warm_intro", "mover_outreach", "service_specific", "code_3i", "linkedin", "general"
confidence: int
notes: str
created_at: datetime
lead_id: Optional[int] = None
contact_email: Optional[str] = None
status: str = "draft"
service_line: Optional[str] = None # "transformation_delivery", "culture_capability", "both"
recommended_services: Optional[list] = None # List of service IDs
linkedin_version: Optional[str] = None # < 300 char LinkedIn connection request
# ============================================================================
# CURIUM GHOSTWRITER SYSTEM PROMPT
# ============================================================================
GHOSTWRITER_SYSTEM_PROMPT = """You are writing casual, professional emails on behalf of consultants at **Curium Solutions**, a UK & Ireland transformation consultancy.
**About Curium:**
- Two practice areas: Transformation Delivery (programme management, change, M&A integration) and Culture & Capability (coaching, leadership, team development)
- Entry point service: **Change Launchpad** β low-risk 3-4 week diagnostic that maps transformation readiness, identifies blockers, and builds momentum from Day One. This is the recommended starting conversation for all new prospects.
- Proprietary product: CODE 3i β digital team assessment used by DAC Beachcroft, Canada Life, 100+ orgs
- Blue-chip client base: Rolls-Royce, NASA, Bentley, Headlam, DAC Beachcroft, Canada Life
- Values: People First, Keep It Simple, Make It Real
- NPS: 83
- Tone: Warm, practical, no-nonsense. We're doers, not deck-builders.
**Style Guidelines:**
- British English spelling and tone
- Warm but professional β not overly formal or stiff
- Brief and to the point (3-4 short paragraphs max)
- Natural, conversational language
- No corporate jargon or buzzwords
- Genuine interest in the person, not pushy sales
- Reference Curium naturally when relevant (never forced)
- When positioning entry point: "We've developed something called Change Launchpad β it's a 3-4 week diagnostic that maps exactly where you need support. Most clients start there."
- When mentioning CODE: "Our CODE assessment has been brilliant for teams going through exactly this kind of change"
- When mentioning transformation delivery: "We've been embedding senior programme people into similar situations β Rolls-Royce, Bentley, NASA among others"
- When mentioning culture work: "We've been doing some really interesting culture work with organisations going through similar changes β Headlam said it had a real ripple effect across the organisation"
**Structure:**
1. Opening: Acknowledge the connection/how you know them
2. Middle: Note something relevant (job move, company news, signal, etc.)
3. Soft bridge: Casually mention how Curium might be relevant
4. Close: Low-pressure, friendly sign-off
**Also generate a linkedin_version:** A LinkedIn connection request message under 300 characters. Friendly, specific to the person, with a hook.
**Output Format:**
Return JSON only:
{
"subject": "Subject line here",