import os, requests, time
KL_KEY = os.environ["KLAVIYO_API_KEY"]
MV = os.environ["MAVERA_API_KEY"]
MB = "https://app.mavera.io/api/v1"
MH = {"Authorization": f"Bearer {MV}", "Content-Type": "application/json"}
KH = {
"Authorization": f"Klaviyo-API-Key {KL_KEY}",
"Content-Type": "application/json",
"revision": "2024-10-15",
}
r = requests.get(f"https://a.klaviyo.com/api/flows", headers=KH, params={
"fields[flow]": "name,status,trigger_type",
})
if r.status_code == 429:
time.sleep(int(r.headers.get("Retry-After", 10)))
r = requests.get(f"https://a.klaviyo.com/api/flows", headers=KH, params={
"fields[flow]": "name,status,trigger_type",
})
r.raise_for_status()
flows = r.json().get("data", [])
print(f"Found {len(flows)} flows\n")
flow_metrics = []
for flow in flows[:10]:
flow_id = flow["id"]
flow_name = flow["attributes"]["name"]
flow_status = flow["attributes"].get("status", "unknown")
metrics_r = requests.post(
f"https://a.klaviyo.com/api/metric-aggregates",
headers=KH,
json={
"data": {
"type": "metric-aggregate",
"attributes": {
"metric_id": "open",
"measurements": ["count", "unique"],
"interval": "month",
"page_size": 1,
"filter": [f"equals(flow_id,'{flow_id}')"],
"timeframe": {"key": "last_30_days"},
},
},
},
)
open_data = {}
if metrics_r.status_code == 200:
agg = metrics_r.json().get("data", {}).get("attributes", {})
open_data = {"opens": agg.get("data", [{}])[0] if agg.get("data") else {}}
flow_metrics.append({
"id": flow_id,
"name": flow_name,
"status": flow_status,
"metrics": open_data,
})
time.sleep(0.5)
BENCHMARK = {"open_rate": 0.25, "click_rate": 0.035}
UNDERPERFORMERS = [
{"name": "Welcome Series", "open_rate": 0.18, "click_rate": 0.02, "current_subject": "Welcome to our family!", "current_preview": "Here's what to expect..."},
{"name": "Abandoned Cart", "open_rate": 0.15, "click_rate": 0.025, "current_subject": "You forgot something!", "current_preview": "Complete your purchase"},
{"name": "Post-Purchase", "open_rate": 0.22, "click_rate": 0.018, "current_subject": "Thanks for your order", "current_preview": "Your order details inside"},
]
BRAND_VOICE_ID = os.environ.get("BRAND_VOICE_ID", "")
print("--- Flow Content Refresh ---\n")
for flow in UNDERPERFORMERS:
prompt = (
f"Rewrite the email content for our '{flow['name']}' flow. "
f"Current performance is below benchmark:\n"
f" Open rate: {flow['open_rate']:.0%} (benchmark: {BENCHMARK['open_rate']:.0%})\n"
f" Click rate: {flow['click_rate']:.0%} (benchmark: {BENCHMARK['click_rate']:.0%})\n\n"
f"Current subject: \"{flow['current_subject']}\"\n"
f"Current preview: \"{flow['current_preview']}\"\n\n"
f"Generate:\n"
f"1. 3 subject line variants (each under 50 chars)\n"
f"2. Preview text for each (under 90 chars)\n"
f"3. Email body rewrite (150-200 words) that:\n"
f" - Hooks in the first line\n"
f" - Addresses the reader's emotional state at this flow stage\n"
f" - Has a clear, compelling CTA\n"
f"4. Explain what's wrong with the current version"
)
payload = {"prompt": prompt}
if BRAND_VOICE_ID:
payload["brand_voice_id"] = BRAND_VOICE_ID
gen = requests.post(f"{MB}/generations", headers=MH, json=payload).json()
print(f"{'='*50}")
print(f"Flow: {flow['name']}")
print(f"Current: {flow['open_rate']:.0%} open / {flow['click_rate']:.0%} click")
print(f"{'='*50}")
print(gen.get("output", gen.get("content", ""))[:700])
print()
time.sleep(0.5)