Spaces:
Sleeping
Sleeping
File size: 38,477 Bytes
aa0f1ab 7922906 aa0f1ab 7922906 aa0f1ab 7922906 aa0f1ab 7922906 aa0f1ab 9c6926e 7922906 9c6926e 7922906 9c6926e 7922906 9c6926e 7922906 aa0f1ab 7922906 aa0f1ab 7922906 9c6926e 7922906 9c6926e aa0f1ab 7922906 aa0f1ab 7922906 aa0f1ab 7922906 aa0f1ab b8f40ca aa0f1ab 7922906 aa0f1ab 7922906 aa0f1ab 7922906 aa0f1ab b8f40ca aa0f1ab 7922906 aa0f1ab 7922906 aa0f1ab 7922906 aa0f1ab 7922906 aa0f1ab 7922906 b8f40ca 7922906 aa0f1ab 7922906 aa0f1ab 7922906 aa0f1ab 7922906 b8f40ca 7922906 b8f40ca 7922906 b8f40ca 7922906 b8f40ca 7922906 9c6926e 7922906 aa0f1ab 7922906 aa0f1ab 7922906 aa0f1ab 7922906 aa0f1ab 7922906 aa0f1ab 7922906 aa0f1ab 7922906 aa0f1ab 7922906 aa0f1ab e94e59d 7922906 e94e59d 7922906 e94e59d 7922906 e94e59d 7922906 e94e59d 7922906 e94e59d 7922906 e94e59d 7922906 e94e59d 7922906 aa0f1ab 7922906 aa0f1ab 7922906 aa0f1ab 7922906 aa0f1ab 7922906 aa0f1ab 7922906 aa0f1ab 7922906 aa0f1ab 7922906 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 | """
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}")
|