import os, requests, time
from datetime import datetime, timedelta
TW_SID = os.environ["TWILIO_ACCOUNT_SID"]
TW_TOKEN = os.environ["TWILIO_AUTH_TOKEN"]
TW_AUTH = (TW_SID, TW_TOKEN)
TW_CONV = "https://conversations.twilio.com/v1"
MV = os.environ["MAVERA_API_KEY"]
MV_BASE = "https://app.mavera.io/api/v1"
MV_H = {"Authorization": f"Bearer {MV}", "Content-Type": "application/json"}
# 1. List recent conversations
r = requests.get(f"{TW_CONV}/Conversations", auth=TW_AUTH,
params={"PageSize": 50})
r.raise_for_status()
conversations = r.json().get("conversations", [])
print(f"Found {len(conversations)} conversations")
# 2. Fetch messages for each conversation
all_threads = []
for conv in conversations[:30]:
sid = conv.get("sid", "")
label = conv.get("friendly_name", conv.get("unique_name", sid))
mr = requests.get(f"{TW_CONV}/Conversations/{sid}/Messages", auth=TW_AUTH,
params={"PageSize": 50, "Order": "asc"})
if not mr.ok:
continue
msgs = mr.json().get("messages", [])
thread_msgs = []
for m in msgs:
thread_msgs.append({
"author": m.get("author", "unknown"),
"body": m.get("body", "")[:300],
"date": m.get("date_created", "")[:16],
})
if thread_msgs:
all_threads.append({"label": label, "input": thread_msgs,
"msg_count": len(thread_msgs)})
time.sleep(0.1)
print(f"Threads with input: {len(all_threads)}, "
f"Total input: {sum(t['msg_count'] for t in all_threads)}")
# 3. Build corpus
corpus = []
for t in all_threads[:20]:
corpus.append(f"\n--- THREAD: {t['label']} ({t['msg_count']} messages) ---")
for m in t["messages"]:
corpus.append(f"[{m['date']}] {m['author']}: {m['body']}")
corpus_text = "\n".join(corpus)
# 4. Mave analysis
analysis = requests.post(f"{MV_BASE}/mave/chat", headers=MV_H, json={
"message": f"Conversation intelligence analyst. Analyze {len(all_threads)} SMS conversation threads ({sum(t['msg_count'] for t in all_threads)} total messages).\n\n"
f"{corpus_text[:8000]}\n\n"
"Produce a CONVERSATION INTELLIGENCE REPORT:\n\n"
"1. **Response Patterns** — Average messages per thread, response time distribution, who initiates\n"
"2. **Sentiment Analysis** — Overall tone, sentiment shifts within threads, frustration signals\n"
"3. **Drop-off Points** — Where conversations end prematurely, common last messages before silence\n"
"4. **Top Intents** — What customers are asking about (categories with counts)\n"
"5. **Winning Messages** — Our messages that get the best responses (highest engagement)\n"
"6. **Problem Messages** — Our messages that cause confusion, no-reply, or negative reactions\n"
"7. **Optimization Recommendations** — 5 specific changes to improve conversion/satisfaction\n\n"
"Include representative quotes."
}).json()
print(f"\n{'='*60}\nSMS CONVERSATION INTELLIGENCE\n{'='*60}")
print(analysis.get("content", "")[:3000])