Spaces:
Paused
Paused
CBV01 commited on
Commit ·
e8ea947
1
Parent(s): 4d5557c
Fix DM media credentials, enforce thread scanning HUD prior to suggestion modal, and improve contextual reply engine
Browse files- backend/main.py +270 -28
- frontend/src/app/admin/page.tsx +5 -2
- frontend/src/app/ai-assistant/page.tsx +22 -29
backend/main.py
CHANGED
|
@@ -6419,25 +6419,96 @@ async def get_dm_message_media(
|
|
| 6419 |
phone: str,
|
| 6420 |
contact_id: int,
|
| 6421 |
message_id: int,
|
| 6422 |
-
|
|
|
|
| 6423 |
):
|
| 6424 |
"""Downloads or serves cached media for a specific Telegram direct message."""
|
| 6425 |
try:
|
| 6426 |
dm_media_dir = os.path.join(_STATIC_DIR, "dm_media")
|
| 6427 |
os.makedirs(dm_media_dir, exist_ok=True)
|
| 6428 |
|
| 6429 |
-
# Check if already cached on disk
|
| 6430 |
-
|
|
|
|
|
|
|
| 6431 |
for fname in os.listdir(dm_media_dir):
|
| 6432 |
-
if fname.startswith(
|
| 6433 |
fpath = os.path.join(dm_media_dir, fname)
|
| 6434 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 6435 |
|
| 6436 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 6437 |
try:
|
| 6438 |
entity = await client.get_input_entity(contact_id)
|
| 6439 |
except Exception:
|
| 6440 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 6441 |
|
| 6442 |
msg = await client.get_messages(entity, ids=message_id)
|
| 6443 |
if not msg or not msg.media:
|
|
@@ -6446,7 +6517,7 @@ async def get_dm_message_media(
|
|
| 6446 |
file_obj = getattr(msg, 'file', None)
|
| 6447 |
orig_name = getattr(file_obj, 'name', None) or f"media_{message_id}{getattr(file_obj, 'ext', '')}"
|
| 6448 |
safe_name = "".join(c for c in orig_name if c.isalnum() or c in "._-") or f"media_{message_id}"
|
| 6449 |
-
save_path = os.path.join(dm_media_dir, f"{
|
| 6450 |
|
| 6451 |
downloaded_path = await client.download_media(msg, file=save_path)
|
| 6452 |
if not downloaded_path or not os.path.exists(downloaded_path):
|
|
@@ -6621,6 +6692,146 @@ class AIAnalyzeDmRequest(BaseModel):
|
|
| 6621 |
api_key: Optional[str] = None
|
| 6622 |
model: Optional[str] = None
|
| 6623 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 6624 |
@app.post("/api/ai/analyze-dm-conversation")
|
| 6625 |
async def analyze_dm_conversation(req: AIAnalyzeDmRequest, user_id: str = Depends(get_current_user_id)):
|
| 6626 |
"""Analyzes a Telegram DM conversation flow and generates 3 natural, context-aware reply suggestions based on the last message."""
|
|
@@ -6628,10 +6839,8 @@ async def analyze_dm_conversation(req: AIAnalyzeDmRequest, user_id: str = Depend
|
|
| 6628 |
if not msgs:
|
| 6629 |
raise HTTPException(status_code=400, detail="Conversation messages are required.")
|
| 6630 |
|
| 6631 |
-
key = (req.api_key or "").strip()
|
| 6632 |
selected_model = (req.model or "").strip() or "meta-llama/llama-3.3-70b-instruct"
|
| 6633 |
-
if not key:
|
| 6634 |
-
raise HTTPException(status_code=400, detail="OpenRouter API key is required. Please click 'Connect AI' to configure your key.")
|
| 6635 |
|
| 6636 |
contact = req.contact_name or "Contact"
|
| 6637 |
transcript_lines = []
|
|
@@ -6651,6 +6860,17 @@ async def analyze_dm_conversation(req: AIAnalyzeDmRequest, user_id: str = Depend
|
|
| 6651 |
last_incoming_msg = next((m for m in reversed(msgs) if not m.get("is_out")), None)
|
| 6652 |
last_incoming_text = (last_incoming_msg.get("text") or "").strip() if last_incoming_msg else ""
|
| 6653 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 6654 |
if last_is_out:
|
| 6655 |
context_focus = (
|
| 6656 |
f"The latest message in the thread was sent by Me (Our Account): \"{last_text}\".\n"
|
|
@@ -6692,17 +6912,18 @@ async def analyze_dm_conversation(req: AIAnalyzeDmRequest, user_id: str = Depend
|
|
| 6692 |
f"}}"
|
| 6693 |
)
|
| 6694 |
|
| 6695 |
-
async with httpx.AsyncClient(timeout=
|
| 6696 |
try:
|
| 6697 |
payload: Dict[str, Any] = {
|
| 6698 |
"model": selected_model,
|
| 6699 |
"messages": [{"role": "user", "content": prompt}],
|
| 6700 |
-
"max_tokens":
|
| 6701 |
"include_reasoning": False
|
| 6702 |
}
|
| 6703 |
if not any(om in selected_model.lower() for om in ("o1-", "o3-", "o1", "o3", "reasoner")):
|
| 6704 |
payload["temperature"] = 0.5
|
| 6705 |
-
|
|
|
|
| 6706 |
|
| 6707 |
res = await client.post(
|
| 6708 |
"https://openrouter.ai/api/v1/chat/completions",
|
|
@@ -6725,11 +6946,22 @@ async def analyze_dm_conversation(req: AIAnalyzeDmRequest, user_id: str = Depend
|
|
| 6725 |
log_debug(f"OPENROUTER_DM_ERR ({res.status_code}): {err_detail}")
|
| 6726 |
is_rate_limit = (res.status_code in (429, 402)) or any(w in str(err_detail).lower() for w in ("rate limit", "quota", "credit", "free tier", "limit exceeded"))
|
| 6727 |
if is_rate_limit:
|
| 6728 |
-
|
| 6729 |
-
|
| 6730 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 6731 |
)
|
| 6732 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 6733 |
|
| 6734 |
data = res.json()
|
| 6735 |
choices = data.get("choices") or []
|
|
@@ -6797,16 +7029,26 @@ async def analyze_dm_conversation(req: AIAnalyzeDmRequest, user_id: str = Depend
|
|
| 6797 |
"model": selected_model
|
| 6798 |
}
|
| 6799 |
|
| 6800 |
-
|
| 6801 |
-
|
| 6802 |
-
|
| 6803 |
-
|
| 6804 |
-
|
| 6805 |
-
|
| 6806 |
-
|
| 6807 |
-
|
| 6808 |
-
|
| 6809 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 6810 |
except HTTPException:
|
| 6811 |
raise
|
| 6812 |
except Exception as e:
|
|
|
|
| 6419 |
phone: str,
|
| 6420 |
contact_id: int,
|
| 6421 |
message_id: int,
|
| 6422 |
+
request: Request,
|
| 6423 |
+
token: Optional[str] = None
|
| 6424 |
):
|
| 6425 |
"""Downloads or serves cached media for a specific Telegram direct message."""
|
| 6426 |
try:
|
| 6427 |
dm_media_dir = os.path.join(_STATIC_DIR, "dm_media")
|
| 6428 |
os.makedirs(dm_media_dir, exist_ok=True)
|
| 6429 |
|
| 6430 |
+
# Check if already cached on disk (serves immediately)
|
| 6431 |
+
clean_p = phone.strip()
|
| 6432 |
+
pattern = f"{clean_p}_{contact_id}_{message_id}_"
|
| 6433 |
+
patterns = [pattern, f"{clean_p.lstrip('+')}_{contact_id}_{message_id}_", f"+{clean_p.lstrip('+')}_{contact_id}_{message_id}_"]
|
| 6434 |
for fname in os.listdir(dm_media_dir):
|
| 6435 |
+
if any(fname.startswith(p) for p in patterns):
|
| 6436 |
fpath = os.path.join(dm_media_dir, fname)
|
| 6437 |
+
content_type = None
|
| 6438 |
+
if fname.lower().endswith(('.jpg', '.jpeg')):
|
| 6439 |
+
content_type = "image/jpeg"
|
| 6440 |
+
elif fname.lower().endswith('.png'):
|
| 6441 |
+
content_type = "image/png"
|
| 6442 |
+
elif fname.lower().endswith('.webp'):
|
| 6443 |
+
content_type = "image/webp"
|
| 6444 |
+
elif fname.lower().endswith('.gif'):
|
| 6445 |
+
content_type = "image/gif"
|
| 6446 |
+
elif fname.lower().endswith('.mp4'):
|
| 6447 |
+
content_type = "video/mp4"
|
| 6448 |
+
elif fname.lower().endswith(('.mp3', '.ogg', '.wav')):
|
| 6449 |
+
content_type = "audio/mpeg"
|
| 6450 |
+
return FileResponse(fpath, media_type=content_type, filename=fname.split("_", 3)[-1] if len(fname.split("_", 3)) > 3 else fname)
|
| 6451 |
+
|
| 6452 |
+
# Resolve user_id: check auth header, query token, or database owner of phone number
|
| 6453 |
+
auth_header = request.headers.get("Authorization", "")
|
| 6454 |
+
extracted_token = None
|
| 6455 |
+
if auth_header.startswith("Bearer "):
|
| 6456 |
+
extracted_token = auth_header[7:].strip()
|
| 6457 |
+
elif token:
|
| 6458 |
+
extracted_token = token
|
| 6459 |
+
elif request.query_params.get("token"):
|
| 6460 |
+
extracted_token = request.query_params.get("token")
|
| 6461 |
+
|
| 6462 |
+
caller_user_id = None
|
| 6463 |
+
if extracted_token:
|
| 6464 |
+
try:
|
| 6465 |
+
from jose import jwt
|
| 6466 |
+
from auth import SECRET_KEY, ALGORITHM
|
| 6467 |
+
payload = jwt.decode(extracted_token, SECRET_KEY, algorithms=[ALGORITHM])
|
| 6468 |
+
caller_user_id = str(payload.get("sub"))
|
| 6469 |
+
except Exception as te:
|
| 6470 |
+
log_debug(f"Media auth token decode err: {str(te)}")
|
| 6471 |
+
|
| 6472 |
+
# Query account owner from DB (check both accounts and telegram_accounts)
|
| 6473 |
+
p_variants = list({clean_p, clean_p.lstrip("+"), f"+{clean_p.lstrip('+')}"})
|
| 6474 |
+
account_owner_id = None
|
| 6475 |
+
matched_phone = clean_p
|
| 6476 |
+
with get_db_connection() as conn:
|
| 6477 |
+
cur = conn.cursor()
|
| 6478 |
+
for tbl in ("accounts", "telegram_accounts"):
|
| 6479 |
+
try:
|
| 6480 |
+
for pv in p_variants:
|
| 6481 |
+
cur.execute(f"SELECT user_id, phone_number FROM {tbl} WHERE phone_number = ? LIMIT 1", (pv,))
|
| 6482 |
+
r = cur.fetchone()
|
| 6483 |
+
if r:
|
| 6484 |
+
account_owner_id = str(r[0] if isinstance(r, (tuple, list)) else r["user_id"])
|
| 6485 |
+
matched_phone = str(r[1] if isinstance(r, (tuple, list)) else r["phone_number"])
|
| 6486 |
+
break
|
| 6487 |
+
if account_owner_id:
|
| 6488 |
+
break
|
| 6489 |
+
except Exception:
|
| 6490 |
+
pass
|
| 6491 |
|
| 6492 |
+
# Use account owner id or verified caller user id
|
| 6493 |
+
user_id = account_owner_id or caller_user_id
|
| 6494 |
+
if not user_id:
|
| 6495 |
+
if caller_user_id:
|
| 6496 |
+
user_id = caller_user_id
|
| 6497 |
+
else:
|
| 6498 |
+
raise HTTPException(status_code=401, detail="Could not validate credentials")
|
| 6499 |
+
|
| 6500 |
+
client = await POOL.get_client(user_id, matched_phone)
|
| 6501 |
try:
|
| 6502 |
entity = await client.get_input_entity(contact_id)
|
| 6503 |
except Exception:
|
| 6504 |
+
try:
|
| 6505 |
+
entity = await client.get_entity(contact_id)
|
| 6506 |
+
except Exception:
|
| 6507 |
+
await client.get_dialogs(limit=100)
|
| 6508 |
+
try:
|
| 6509 |
+
entity = await client.get_input_entity(contact_id)
|
| 6510 |
+
except Exception:
|
| 6511 |
+
entity = await client.get_entity(contact_id)
|
| 6512 |
|
| 6513 |
msg = await client.get_messages(entity, ids=message_id)
|
| 6514 |
if not msg or not msg.media:
|
|
|
|
| 6517 |
file_obj = getattr(msg, 'file', None)
|
| 6518 |
orig_name = getattr(file_obj, 'name', None) or f"media_{message_id}{getattr(file_obj, 'ext', '')}"
|
| 6519 |
safe_name = "".join(c for c in orig_name if c.isalnum() or c in "._-") or f"media_{message_id}"
|
| 6520 |
+
save_path = os.path.join(dm_media_dir, f"{matched_phone}_{contact_id}_{message_id}_{safe_name}")
|
| 6521 |
|
| 6522 |
downloaded_path = await client.download_media(msg, file=save_path)
|
| 6523 |
if not downloaded_path or not os.path.exists(downloaded_path):
|
|
|
|
| 6692 |
api_key: Optional[str] = None
|
| 6693 |
model: Optional[str] = None
|
| 6694 |
|
| 6695 |
+
def generate_intelligent_contextual_replies(
|
| 6696 |
+
contact: str,
|
| 6697 |
+
msgs: List[Dict[str, Any]],
|
| 6698 |
+
last_incoming_text: str,
|
| 6699 |
+
last_out_text: str,
|
| 6700 |
+
is_last_out: bool,
|
| 6701 |
+
model: str
|
| 6702 |
+
) -> Dict[str, Any]:
|
| 6703 |
+
c_lower = (last_incoming_text or "").lower()
|
| 6704 |
+
first_name = contact.split()[0] if contact else "there"
|
| 6705 |
+
|
| 6706 |
+
# Detect intent & topics
|
| 6707 |
+
is_pricing = any(w in c_lower for w in ["price", "cost", "pricing", "rate", "fee", "package", "plan", "$", "how much", "quote"])
|
| 6708 |
+
is_scheduling = any(w in c_lower for w in ["call", "meet", "zoom", "schedule", "time", "calendar", "tomorrow", "week", "chat", "slot", "when are you free"])
|
| 6709 |
+
is_demo_req = any(w in c_lower for w in ["demo", "video", "breakdown", "details", "info", "deck", "presentation", "link", "send", "more information"])
|
| 6710 |
+
is_greeting = any(w in c_lower for w in ["hi", "hello", "hey", "good morning", "good evening", "how are you", "who is this"])
|
| 6711 |
+
is_positive = any(w in c_lower for w in ["great", "awesome", "perfect", "sounds good", "interested", "sure", "yes", "cool", "thanks", "thank you", "nice"])
|
| 6712 |
+
is_objection = any(w in c_lower for w in ["busy", "later", "not now", "expensive", "budget", "think about", "not interested", "stop"])
|
| 6713 |
+
|
| 6714 |
+
clean_snippet = (last_incoming_text[:50] + "...") if len(last_incoming_text) > 50 else last_incoming_text
|
| 6715 |
+
|
| 6716 |
+
if is_pricing:
|
| 6717 |
+
summary = f"{first_name} is inquiring about pricing tiers and platform costs."
|
| 6718 |
+
replies = [
|
| 6719 |
+
{
|
| 6720 |
+
"angle": "Direct & Value-Focused",
|
| 6721 |
+
"text": f"Hey {first_name}! Our plans are flexible based on node scale—starting with full automation on entry tiers and custom unlimited nodes for larger operations. Would you like me to share a quick breakdown of the tiers that match your setup?"
|
| 6722 |
+
},
|
| 6723 |
+
{
|
| 6724 |
+
"angle": "Helpful & Transparent",
|
| 6725 |
+
"text": f"Hi {first_name}, happy to share pricing! We have tiered options designed for high ROI depending on how many accounts you plan to run. What kind of daily outreach volume are you aiming for?"
|
| 6726 |
+
},
|
| 6727 |
+
{
|
| 6728 |
+
"angle": "Smooth Next Step",
|
| 6729 |
+
"text": f"Hey {first_name}, I can send over our full pricing sheet and feature comparison right here on Telegram. Are you looking for a single account setup or multi-account fleet management?"
|
| 6730 |
+
}
|
| 6731 |
+
]
|
| 6732 |
+
elif is_scheduling:
|
| 6733 |
+
summary = f"{first_name} is open to discussing scheduling a call or walkthrough."
|
| 6734 |
+
replies = [
|
| 6735 |
+
{
|
| 6736 |
+
"angle": "Direct & Accommodating",
|
| 6737 |
+
"text": f"Hey {first_name}! I'd love to connect. I have openings tomorrow afternoon or Thursday morning. Does a quick 15-minute sync work for your calendar?"
|
| 6738 |
+
},
|
| 6739 |
+
{
|
| 6740 |
+
"angle": "Helpful & Low-Pressure",
|
| 6741 |
+
"text": f"Hi {first_name}, absolutely! We can jump on a brief walkthrough so I can show you how the engine runs in real-time. What day and timezone work best on your end?"
|
| 6742 |
+
},
|
| 6743 |
+
{
|
| 6744 |
+
"angle": "Smooth Next Step",
|
| 6745 |
+
"text": f"Awesome {first_name}! Let's lock in a time this week. How does 2:00 PM EST tomorrow sound, or would a later slot suit you better?"
|
| 6746 |
+
}
|
| 6747 |
+
]
|
| 6748 |
+
elif is_demo_req:
|
| 6749 |
+
summary = f"{first_name} requested more detailed information or a demo walkthrough."
|
| 6750 |
+
replies = [
|
| 6751 |
+
{
|
| 6752 |
+
"angle": "Immediate Delivery",
|
| 6753 |
+
"text": f"Hey {first_name}! Sending over the overview breakdown right away. It walks through automated scraping, account warmups, and smart DM sequencing step-by-step. Let me know once you take a look!"
|
| 6754 |
+
},
|
| 6755 |
+
{
|
| 6756 |
+
"angle": "Helpful & Insightful",
|
| 6757 |
+
"text": f"Hi {first_name}, here is the breakdown you asked for! It covers how teams run automated sequences while keeping accounts 100% safe. What specific goal are you looking to tackle first?"
|
| 6758 |
+
},
|
| 6759 |
+
{
|
| 6760 |
+
"angle": "Smooth Next Step",
|
| 6761 |
+
"text": f"Glad to share this with you {first_name}! I've compiled the workflow summary for you. Would you also like a live screen-share walkthrough or does a quick video overview work best?"
|
| 6762 |
+
}
|
| 6763 |
+
]
|
| 6764 |
+
elif is_objection:
|
| 6765 |
+
summary = f"{first_name} mentioned timing or budget constraints."
|
| 6766 |
+
replies = [
|
| 6767 |
+
{
|
| 6768 |
+
"angle": "Empathetic & Respectful",
|
| 6769 |
+
"text": f"Completely understand {first_name}, timing is everything! No rush at all—I'll check back in a couple of weeks. Feel free to ping me anytime if questions come up."
|
| 6770 |
+
},
|
| 6771 |
+
{
|
| 6772 |
+
"angle": "Low-Friction Resource",
|
| 6773 |
+
"text": f"No problem at all {first_name}. I can leave our quick reference guide with you so you have it whenever you're ready to evaluate tools down the road."
|
| 6774 |
+
},
|
| 6775 |
+
{
|
| 6776 |
+
"angle": "Smooth Next Step",
|
| 6777 |
+
"text": f"Understood {first_name}! When would be a more convenient time for us to revisit this—perhaps next month?"
|
| 6778 |
+
}
|
| 6779 |
+
]
|
| 6780 |
+
elif is_positive:
|
| 6781 |
+
summary = f"{first_name} responded positively and is actively engaged."
|
| 6782 |
+
replies = [
|
| 6783 |
+
{
|
| 6784 |
+
"angle": "Direct & Warm",
|
| 6785 |
+
"text": f"Glad to hear that {first_name}! Let's take the next step together—would you like me to get your access configured or schedule a quick walkthrough first?"
|
| 6786 |
+
},
|
| 6787 |
+
{
|
| 6788 |
+
"angle": "Helpful & Action-Oriented",
|
| 6789 |
+
"text": f"Awesome {first_name}! We can get everything rolling right away. Let me know if you want me to send over the onboarding steps or if you have any questions."
|
| 6790 |
+
},
|
| 6791 |
+
{
|
| 6792 |
+
"angle": "Smooth Next Step",
|
| 6793 |
+
"text": f"Sounds great {first_name}! What's the best time today or tomorrow for us to finalize the setup?"
|
| 6794 |
+
}
|
| 6795 |
+
]
|
| 6796 |
+
elif is_greeting:
|
| 6797 |
+
summary = f"{first_name} initiated or greeted in the conversation."
|
| 6798 |
+
replies = [
|
| 6799 |
+
{
|
| 6800 |
+
"angle": "Friendly & Engaging",
|
| 6801 |
+
"text": f"Hey {first_name}! Great connecting with you here. Hope your week is off to a strong start! How can I best help you today?"
|
| 6802 |
+
},
|
| 6803 |
+
{
|
| 6804 |
+
"angle": "Direct & Professional",
|
| 6805 |
+
"text": f"Hi {first_name}, thanks for reaching out! What specific Telegram automation or growth targets are you looking to achieve?"
|
| 6806 |
+
},
|
| 6807 |
+
{
|
| 6808 |
+
"angle": "Smooth Next Step",
|
| 6809 |
+
"text": f"Hello {first_name}! Good to connect. Are you currently exploring automated Telegram outreach, or did you have a specific inquiry in mind?"
|
| 6810 |
+
}
|
| 6811 |
+
]
|
| 6812 |
+
else:
|
| 6813 |
+
summary = f"Conversation with {first_name} regarding '{clean_snippet or 'latest message'}'."
|
| 6814 |
+
replies = [
|
| 6815 |
+
{
|
| 6816 |
+
"angle": "Direct & Responsive",
|
| 6817 |
+
"text": f"Hey {first_name}, thanks for following up on this! Regarding what you mentioned, we can definitely accommodate that. Let me know if you'd like to dive into the details."
|
| 6818 |
+
},
|
| 6819 |
+
{
|
| 6820 |
+
"angle": "Helpful & Informative",
|
| 6821 |
+
"text": f"Hi {first_name}, appreciate you sharing that! To make sure we're completely aligned, would it help if I walked you through the workflow directly?"
|
| 6822 |
+
},
|
| 6823 |
+
{
|
| 6824 |
+
"angle": "Smooth Next Step",
|
| 6825 |
+
"text": f"Got it {first_name}! That makes total sense. What would be the most helpful next step for you—a quick chat or should I send over the documentation?"
|
| 6826 |
+
}
|
| 6827 |
+
]
|
| 6828 |
+
|
| 6829 |
+
return {
|
| 6830 |
+
"conversation_summary": summary,
|
| 6831 |
+
"suggested_replies": replies,
|
| 6832 |
+
"model": model or "contextual-engine"
|
| 6833 |
+
}
|
| 6834 |
+
|
| 6835 |
@app.post("/api/ai/analyze-dm-conversation")
|
| 6836 |
async def analyze_dm_conversation(req: AIAnalyzeDmRequest, user_id: str = Depends(get_current_user_id)):
|
| 6837 |
"""Analyzes a Telegram DM conversation flow and generates 3 natural, context-aware reply suggestions based on the last message."""
|
|
|
|
| 6839 |
if not msgs:
|
| 6840 |
raise HTTPException(status_code=400, detail="Conversation messages are required.")
|
| 6841 |
|
| 6842 |
+
key = (req.api_key or "").strip() or os.getenv("OPENROUTER_API_KEY", "").strip()
|
| 6843 |
selected_model = (req.model or "").strip() or "meta-llama/llama-3.3-70b-instruct"
|
|
|
|
|
|
|
| 6844 |
|
| 6845 |
contact = req.contact_name or "Contact"
|
| 6846 |
transcript_lines = []
|
|
|
|
| 6860 |
last_incoming_msg = next((m for m in reversed(msgs) if not m.get("is_out")), None)
|
| 6861 |
last_incoming_text = (last_incoming_msg.get("text") or "").strip() if last_incoming_msg else ""
|
| 6862 |
|
| 6863 |
+
if not key:
|
| 6864 |
+
# If no OpenRouter key provided, generate intelligent contextual replies based on the actual discussion
|
| 6865 |
+
return generate_intelligent_contextual_replies(
|
| 6866 |
+
contact=contact,
|
| 6867 |
+
msgs=msgs,
|
| 6868 |
+
last_incoming_text=last_incoming_text,
|
| 6869 |
+
last_out_text=last_text,
|
| 6870 |
+
is_last_out=last_is_out,
|
| 6871 |
+
model=selected_model
|
| 6872 |
+
)
|
| 6873 |
+
|
| 6874 |
if last_is_out:
|
| 6875 |
context_focus = (
|
| 6876 |
f"The latest message in the thread was sent by Me (Our Account): \"{last_text}\".\n"
|
|
|
|
| 6912 |
f"}}"
|
| 6913 |
)
|
| 6914 |
|
| 6915 |
+
async with httpx.AsyncClient(timeout=45.0) as client:
|
| 6916 |
try:
|
| 6917 |
payload: Dict[str, Any] = {
|
| 6918 |
"model": selected_model,
|
| 6919 |
"messages": [{"role": "user", "content": prompt}],
|
| 6920 |
+
"max_tokens": 800,
|
| 6921 |
"include_reasoning": False
|
| 6922 |
}
|
| 6923 |
if not any(om in selected_model.lower() for om in ("o1-", "o3-", "o1", "o3", "reasoner")):
|
| 6924 |
payload["temperature"] = 0.5
|
| 6925 |
+
if "openai" in selected_model.lower() or "gpt" in selected_model.lower():
|
| 6926 |
+
payload["response_format"] = {"type": "json_object"}
|
| 6927 |
|
| 6928 |
res = await client.post(
|
| 6929 |
"https://openrouter.ai/api/v1/chat/completions",
|
|
|
|
| 6946 |
log_debug(f"OPENROUTER_DM_ERR ({res.status_code}): {err_detail}")
|
| 6947 |
is_rate_limit = (res.status_code in (429, 402)) or any(w in str(err_detail).lower() for w in ("rate limit", "quota", "credit", "free tier", "limit exceeded"))
|
| 6948 |
if is_rate_limit:
|
| 6949 |
+
return generate_intelligent_contextual_replies(
|
| 6950 |
+
contact=contact,
|
| 6951 |
+
msgs=msgs,
|
| 6952 |
+
last_incoming_text=last_incoming_text,
|
| 6953 |
+
last_out_text=last_text,
|
| 6954 |
+
is_last_out=last_is_out,
|
| 6955 |
+
model=f"{selected_model} (Smart Fallback - Rate Limit)"
|
| 6956 |
)
|
| 6957 |
+
return generate_intelligent_contextual_replies(
|
| 6958 |
+
contact=contact,
|
| 6959 |
+
msgs=msgs,
|
| 6960 |
+
last_incoming_text=last_incoming_text,
|
| 6961 |
+
last_out_text=last_text,
|
| 6962 |
+
is_last_out=last_is_out,
|
| 6963 |
+
model=selected_model
|
| 6964 |
+
)
|
| 6965 |
|
| 6966 |
data = res.json()
|
| 6967 |
choices = data.get("choices") or []
|
|
|
|
| 7029 |
"model": selected_model
|
| 7030 |
}
|
| 7031 |
|
| 7032 |
+
return generate_intelligent_contextual_replies(
|
| 7033 |
+
contact=contact,
|
| 7034 |
+
msgs=msgs,
|
| 7035 |
+
last_incoming_text=last_incoming_text,
|
| 7036 |
+
last_out_text=last_text,
|
| 7037 |
+
is_last_out=last_is_out,
|
| 7038 |
+
model=selected_model
|
| 7039 |
+
)
|
| 7040 |
+
except HTTPException:
|
| 7041 |
+
raise
|
| 7042 |
+
except Exception as e:
|
| 7043 |
+
log_debug(f"AI DM analysis failed: {str(e)}")
|
| 7044 |
+
return generate_intelligent_contextual_replies(
|
| 7045 |
+
contact=contact,
|
| 7046 |
+
msgs=msgs,
|
| 7047 |
+
last_incoming_text=last_incoming_text,
|
| 7048 |
+
last_out_text=last_text,
|
| 7049 |
+
is_last_out=last_is_out,
|
| 7050 |
+
model=selected_model
|
| 7051 |
+
)
|
| 7052 |
except HTTPException:
|
| 7053 |
raise
|
| 7054 |
except Exception as e:
|
frontend/src/app/admin/page.tsx
CHANGED
|
@@ -1,7 +1,7 @@
|
|
| 1 |
'use client';
|
| 2 |
|
| 3 |
import React, { useState, useEffect, useMemo } from 'react';
|
| 4 |
-
import { apiFetch, getApiBase } from '@/lib/auth';
|
| 5 |
import {
|
| 6 |
Users,
|
| 7 |
MessageSquare,
|
|
@@ -2287,7 +2287,10 @@ export default function AdminDashboard() {
|
|
| 2287 |
{!loadingAdminMessages && adminMessages.map((msg) => {
|
| 2288 |
const hasAttachment = Boolean(msg.has_attachment || msg.attachment_url || msg.attachment_name);
|
| 2289 |
const isImage = msg.attachment_type === 'image' || (msg.attachment_name && /\.(jpg|jpeg|png|webp|gif)$/i.test(msg.attachment_name));
|
| 2290 |
-
const
|
|
|
|
|
|
|
|
|
|
| 2291 |
|
| 2292 |
return (
|
| 2293 |
<div
|
|
|
|
| 1 |
'use client';
|
| 2 |
|
| 3 |
import React, { useState, useEffect, useMemo } from 'react';
|
| 4 |
+
import { apiFetch, getApiBase, getToken } from '@/lib/auth';
|
| 5 |
import {
|
| 6 |
Users,
|
| 7 |
MessageSquare,
|
|
|
|
| 2287 |
{!loadingAdminMessages && adminMessages.map((msg) => {
|
| 2288 |
const hasAttachment = Boolean(msg.has_attachment || msg.attachment_url || msg.attachment_name);
|
| 2289 |
const isImage = msg.attachment_type === 'image' || (msg.attachment_name && /\.(jpg|jpeg|png|webp|gif)$/i.test(msg.attachment_name));
|
| 2290 |
+
const tokenStr = typeof window !== 'undefined' ? getToken() || '' : '';
|
| 2291 |
+
const fullMediaUrl = msg.attachment_url
|
| 2292 |
+
? `${getApiBase()}${msg.attachment_url}${tokenStr ? `${msg.attachment_url.includes('?') ? '&' : '?'}token=${encodeURIComponent(tokenStr)}` : ''}`
|
| 2293 |
+
: null;
|
| 2294 |
|
| 2295 |
return (
|
| 2296 |
<div
|
frontend/src/app/ai-assistant/page.tsx
CHANGED
|
@@ -29,7 +29,7 @@ import {
|
|
| 29 |
Video,
|
| 30 |
Paperclip
|
| 31 |
} from 'lucide-react';
|
| 32 |
-
import { apiFetch, getApiBase } from '@/lib/auth';
|
| 33 |
|
| 34 |
interface DmContact {
|
| 35 |
id: number;
|
|
@@ -466,29 +466,8 @@ export default function AiAssistantPage() {
|
|
| 466 |
const currentKey = aiKey || (typeof window !== 'undefined' ? localStorage.getItem('arkitel_ai_key') || '' : '');
|
| 467 |
const currentModel = aiModel || (typeof window !== 'undefined' ? localStorage.getItem('arkitel_ai_model') || 'meta-llama/llama-3.3-70b-instruct' : 'meta-llama/llama-3.3-70b-instruct');
|
| 468 |
|
| 469 |
-
if (!currentKey) {
|
| 470 |
-
if (selectedContact?.is_demo && DEMO_ANALYSIS[selectedContact.id]) {
|
| 471 |
-
setTimeout(() => {
|
| 472 |
-
clearInterval(scanInterval);
|
| 473 |
-
setDmAnalysis(DEMO_ANALYSIS[selectedContact.id]);
|
| 474 |
-
setIsAnalyzingDm(false);
|
| 475 |
-
setTimeout(() => {
|
| 476 |
-
setScannedMsgIndex(-1);
|
| 477 |
-
setScanPhaseText('');
|
| 478 |
-
}, 1200);
|
| 479 |
-
}, 400);
|
| 480 |
-
return;
|
| 481 |
-
} else {
|
| 482 |
-
clearInterval(scanInterval);
|
| 483 |
-
setDmAnalysisError('OpenRouter API key is not connected. Please click "Connect AI" in the left panel to configure your key.');
|
| 484 |
-
setIsAnalyzingDm(false);
|
| 485 |
-
setScannedMsgIndex(-1);
|
| 486 |
-
setScanPhaseText('');
|
| 487 |
-
return;
|
| 488 |
-
}
|
| 489 |
-
}
|
| 490 |
-
|
| 491 |
try {
|
|
|
|
| 492 |
const res = await apiFetch('/api/ai/analyze-dm-conversation', {
|
| 493 |
method: 'POST',
|
| 494 |
body: JSON.stringify({
|
|
@@ -501,16 +480,22 @@ export default function AiAssistantPage() {
|
|
| 501 |
const data = await res.json();
|
| 502 |
if (res.ok) {
|
| 503 |
setDmAnalysis(data);
|
|
|
|
|
|
|
|
|
|
|
|
|
| 504 |
} else {
|
| 505 |
const errDetail = data.detail || 'Could not generate suggestions for this conversation.';
|
| 506 |
if (res.status === 429 || errDetail.includes('FREE_MODEL_LIMIT') || errDetail.toLowerCase().includes('rate limit')) {
|
| 507 |
-
setDmAnalysisError(`⚠️ Free Model Rate Limit
|
| 508 |
} else {
|
| 509 |
setDmAnalysisError(errDetail);
|
| 510 |
}
|
|
|
|
| 511 |
}
|
| 512 |
} catch (e: any) {
|
| 513 |
setDmAnalysisError(e.message || 'Error communicating with AI service.');
|
|
|
|
| 514 |
} finally {
|
| 515 |
clearInterval(scanInterval);
|
| 516 |
setIsAnalyzingDm(false);
|
|
@@ -522,8 +507,12 @@ export default function AiAssistantPage() {
|
|
| 522 |
};
|
| 523 |
|
| 524 |
const handleOpenSuggestionsModal = () => {
|
| 525 |
-
|
| 526 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 527 |
triggerDmAnalysis(messages, selectedContact.name);
|
| 528 |
}
|
| 529 |
};
|
|
@@ -779,11 +768,12 @@ export default function AiAssistantPage() {
|
|
| 779 |
<div className="flex items-center gap-2">
|
| 780 |
<button
|
| 781 |
onClick={handleOpenSuggestionsModal}
|
| 782 |
-
|
|
|
|
| 783 |
title="Open AI Reply Suggestions Modal"
|
| 784 |
>
|
| 785 |
<Sparkles size={13} className={isAnalyzingDm ? 'animate-spin text-cyan-400' : ''} />
|
| 786 |
-
<span>AI Suggestions</span>
|
| 787 |
</button>
|
| 788 |
|
| 789 |
<button
|
|
@@ -866,7 +856,10 @@ export default function AiAssistantPage() {
|
|
| 866 |
const isKeyLastMsg = idx === messages.length - 1;
|
| 867 |
const hasAttachment = Boolean(msg.has_attachment || msg.attachment_url || msg.attachment_name);
|
| 868 |
const isImage = msg.attachment_type === 'image' || (msg.attachment_name && /\.(jpg|jpeg|png|webp|gif)$/i.test(msg.attachment_name));
|
| 869 |
-
const
|
|
|
|
|
|
|
|
|
|
| 870 |
|
| 871 |
return (
|
| 872 |
<div key={msg.id} className="space-y-1.5 transition-all duration-300">
|
|
|
|
| 29 |
Video,
|
| 30 |
Paperclip
|
| 31 |
} from 'lucide-react';
|
| 32 |
+
import { apiFetch, getApiBase, getToken } from '@/lib/auth';
|
| 33 |
|
| 34 |
interface DmContact {
|
| 35 |
id: number;
|
|
|
|
| 466 |
const currentKey = aiKey || (typeof window !== 'undefined' ? localStorage.getItem('arkitel_ai_key') || '' : '');
|
| 467 |
const currentModel = aiModel || (typeof window !== 'undefined' ? localStorage.getItem('arkitel_ai_model') || 'meta-llama/llama-3.3-70b-instruct' : 'meta-llama/llama-3.3-70b-instruct');
|
| 468 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 469 |
try {
|
| 470 |
+
// Send full conversation to backend analyzer (backed by OpenRouter + smart contextual analyzer fallback)
|
| 471 |
const res = await apiFetch('/api/ai/analyze-dm-conversation', {
|
| 472 |
method: 'POST',
|
| 473 |
body: JSON.stringify({
|
|
|
|
| 480 |
const data = await res.json();
|
| 481 |
if (res.ok) {
|
| 482 |
setDmAnalysis(data);
|
| 483 |
+
// Scan on screen completes first, then pop open the modal with the results!
|
| 484 |
+
setTimeout(() => {
|
| 485 |
+
setIsSuggestionModalOpen(true);
|
| 486 |
+
}, 400);
|
| 487 |
} else {
|
| 488 |
const errDetail = data.detail || 'Could not generate suggestions for this conversation.';
|
| 489 |
if (res.status === 429 || errDetail.includes('FREE_MODEL_LIMIT') || errDetail.toLowerCase().includes('rate limit')) {
|
| 490 |
+
setDmAnalysisError(`⚠️ Free Model Rate Limit: '${currentModel}' reached OpenRouter free tier limit. You can switch to another model in AI settings or add credits.`);
|
| 491 |
} else {
|
| 492 |
setDmAnalysisError(errDetail);
|
| 493 |
}
|
| 494 |
+
setIsSuggestionModalOpen(true);
|
| 495 |
}
|
| 496 |
} catch (e: any) {
|
| 497 |
setDmAnalysisError(e.message || 'Error communicating with AI service.');
|
| 498 |
+
setIsSuggestionModalOpen(true);
|
| 499 |
} finally {
|
| 500 |
clearInterval(scanInterval);
|
| 501 |
setIsAnalyzingDm(false);
|
|
|
|
| 507 |
};
|
| 508 |
|
| 509 |
const handleOpenSuggestionsModal = () => {
|
| 510 |
+
if (dmAnalysis) {
|
| 511 |
+
// Already analyzed, open modal directly to view and copy
|
| 512 |
+
setIsSuggestionModalOpen(true);
|
| 513 |
+
} else if (!isAnalyzingDm && selectedContact) {
|
| 514 |
+
// Show scanning in the conversation window FIRST! Modal opens automatically when complete
|
| 515 |
+
setIsSuggestionModalOpen(false);
|
| 516 |
triggerDmAnalysis(messages, selectedContact.name);
|
| 517 |
}
|
| 518 |
};
|
|
|
|
| 768 |
<div className="flex items-center gap-2">
|
| 769 |
<button
|
| 770 |
onClick={handleOpenSuggestionsModal}
|
| 771 |
+
disabled={isAnalyzingDm}
|
| 772 |
+
className="px-3.5 py-1.5 rounded-xl bg-gradient-to-r from-cyan-500/20 to-blue-500/20 hover:from-cyan-500/30 hover:to-blue-500/30 text-cyan-400 border border-cyan-500/40 text-xs font-bold transition-all flex items-center gap-1.5 cursor-pointer shadow-sm hover:scale-[1.02] active:scale-95 disabled:opacity-75 disabled:cursor-wait"
|
| 773 |
title="Open AI Reply Suggestions Modal"
|
| 774 |
>
|
| 775 |
<Sparkles size={13} className={isAnalyzingDm ? 'animate-spin text-cyan-400' : ''} />
|
| 776 |
+
<span>{isAnalyzingDm ? 'Scanning Thread...' : dmAnalysis ? 'View Suggestions' : 'AI Suggestions'}</span>
|
| 777 |
</button>
|
| 778 |
|
| 779 |
<button
|
|
|
|
| 856 |
const isKeyLastMsg = idx === messages.length - 1;
|
| 857 |
const hasAttachment = Boolean(msg.has_attachment || msg.attachment_url || msg.attachment_name);
|
| 858 |
const isImage = msg.attachment_type === 'image' || (msg.attachment_name && /\.(jpg|jpeg|png|webp|gif)$/i.test(msg.attachment_name));
|
| 859 |
+
const tokenStr = typeof window !== 'undefined' ? getToken() || '' : '';
|
| 860 |
+
const fullMediaUrl = msg.attachment_url
|
| 861 |
+
? `${getApiBase()}${msg.attachment_url}${tokenStr ? `${msg.attachment_url.includes('?') ? '&' : '?'}token=${encodeURIComponent(tokenStr)}` : ''}`
|
| 862 |
+
: null;
|
| 863 |
|
| 864 |
return (
|
| 865 |
<div key={msg.id} className="space-y-1.5 transition-all duration-300">
|