CBV01 commited on
Commit
e9969e0
·
1 Parent(s): 90bad1d

Refactor AI Assistant: remove reply textbox, remove diagnose button and ban shield tab, streamline layout, and add contextual copy suggestions

Browse files
backend/main.py CHANGED
@@ -5533,7 +5533,7 @@ class AIAnalyzeDmRequest(BaseModel):
5533
 
5534
  @app.post("/api/ai/analyze-dm-conversation")
5535
  async def analyze_dm_conversation(req: AIAnalyzeDmRequest, user_id: str = Depends(get_current_user_id)):
5536
- """Analyzes a Telegram DM conversation for lead authenticity, buying intent, and 3 strategic closing replies."""
5537
  msgs = req.messages or []
5538
  if not msgs:
5539
  raise HTTPException(status_code=400, detail="Conversation messages are required.")
@@ -5541,38 +5541,63 @@ async def analyze_dm_conversation(req: AIAnalyzeDmRequest, user_id: str = Depend
5541
  key = (req.api_key or "").strip()
5542
  selected_model = (req.model or "").strip() or "meta-llama/llama-3.3-70b-instruct"
5543
  if not key:
5544
- raise HTTPException(status_code=400, detail="OpenRouter API key is required.")
5545
 
5546
- contact = req.contact_name or "Lead"
5547
  transcript_lines = []
5548
  for m in msgs:
5549
- speaker = "Our Account (Me)" if m.get("is_out") else f"Lead ({contact})"
5550
  text_line = (m.get("text") or "").strip()
5551
  if text_line:
5552
  transcript_lines.append(f"{speaker}: {text_line}")
5553
  transcript = "\n".join(transcript_lines) or "No textual messages exchanged yet."
5554
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5555
  prompt = (
5556
- f"You are a brutally realistic, self-aware Telegram sales strategist and deal closer.\n"
5557
- f"Analyze this live 1-on-1 direct message conversation between our account and a lead ({contact}):\n\n"
5558
- f"--- CONVERSATION TRANSCRIPT ---\n"
5559
  f"{transcript}\n"
5560
- f"-------------------------------\n\n"
5561
- f"DIAGNOSIS INSTRUCTIONS:\n"
5562
- f"1. LEAD EVALUATION: Evaluate whether the lead is a Serious Buyer (ready to purchase with real intent), a Tire-Kicker (curious, comparing options, asking endless questions without commitment), or a Time-Waster / Freebie Seeker (wants free access, stalling, or wasting energy).\n"
5563
- f"2. BRUTALLY HONEST VERDICT: Give a realistic, no-fluff verdict in 1-2 sharp sentences. No corporate marketing speak.\n"
5564
- f"3. DYNAMIC UNSCRIPTED REPLIES: Generate 3 realistic, natural Telegram next messages that specifically respond to the last thing said.\n"
5565
- f" CRITICAL RULE ON PAYMENT: DO NOT invent fake bank account details, crypto addresses, or generic payment instructions unless the lead explicitly asked for payment methods in the transcript! Keep replies contextual, conversational, and persuasive.\n\n"
 
 
 
 
 
 
 
5566
  f"Return ONLY valid JSON with this exact structure:\n"
5567
  f"{{\n"
5568
- f' "lead_type": <"Serious Buyer" | "Tire-Kicker" | "Time-Waster / Freebie Seeker">,\n'
5569
- f' "lead_reason": <1-2 sharp, realistic sentences diagnosing their actual behavior and likelihood of closing>,\n'
5570
- f' "buying_intent": <"High (Ready to Close)" | "Warm (Needs Guidance)" | "Low (Browsing / Skeptical)" | "Zero (Time-Waster)">,\n'
5571
- f' "primary_objection": <the exact underlying friction, question, or hesitation they have right now>,\n'
5572
  f' "suggested_replies": [\n'
5573
- f' {{"angle": "Direct Next Step", "text": <natural next message advancing the exact topic toward a close>}},\n'
5574
- f' {{"angle": "Value & Confidence", "text": <answers their doubt or question with high conviction>}},\n'
5575
- f' {{"angle": "Filter / Soft Urgency", "text": <politely filters serious intent without begging or sounding desperate>}}\n'
5576
  f' ]\n'
5577
  f"}}"
5578
  )
@@ -5582,11 +5607,11 @@ async def analyze_dm_conversation(req: AIAnalyzeDmRequest, user_id: str = Depend
5582
  payload: Dict[str, Any] = {
5583
  "model": selected_model,
5584
  "messages": [{"role": "user", "content": prompt}],
5585
- "max_tokens": 3000,
5586
  "include_reasoning": False
5587
  }
5588
  if not any(om in selected_model.lower() for om in ("o1-", "o3-", "o1", "o3", "reasoner")):
5589
- payload["temperature"] = 0.65
5590
 
5591
  res = await client.post(
5592
  "https://openrouter.ai/api/v1/chat/completions",
@@ -5598,40 +5623,50 @@ async def analyze_dm_conversation(req: AIAnalyzeDmRequest, user_id: str = Depend
5598
  },
5599
  json=payload
5600
  )
5601
- if res.status_code == 200:
5602
- data = res.json()
5603
- choices = data.get("choices") or []
5604
- if choices:
5605
- content = choices[0].get("message", {}).get("content") or ""
5606
- content = re.sub(r'<think>[\s\S]*?</think>', '', content, flags=re.IGNORECASE)
5607
- content = re.sub(r'```(?:json)?', '', content).strip('`').strip()
5608
- s = content.find('{')
5609
- e = content.rfind('}')
5610
- if s != -1 and e != -1:
5611
- parsed = json.loads(content[s:e+1])
 
 
 
 
 
 
 
 
 
 
 
 
5612
  return {
5613
- "lead_type": parsed.get("lead_type") or "Interested Lead",
5614
- "lead_reason": parsed.get("lead_reason") or "Inquired about services and active in the conversation.",
5615
- "buying_intent": parsed.get("buying_intent") or "Interested (60%)",
5616
- "primary_objection": parsed.get("primary_objection") or "Awaiting setup details or pricing clarification.",
5617
- "suggested_replies": parsed.get("suggested_replies") or [],
5618
  "model": selected_model
5619
  }
5620
- # Fallback structured replies
 
5621
  return {
5622
- "lead_type": "Interested Lead",
5623
- "lead_reason": "Lead is actively engaging in direct messages.",
5624
- "buying_intent": "Interested (60%)",
5625
- "primary_objection": "Awaiting confirmation and details.",
5626
  "suggested_replies": [
5627
- {"angle": "Direct Close & Order", "text": f"Hey {contact}, I can get you set up with instant access right away. Which package would you like to get started with?"},
5628
- {"angle": "Value, Quality & Proof", "text": f"Our service features 99.9% uptime and 4K quality without buffering. You can test risk-free, and our support team is available 24/7."},
5629
- {"angle": "Freebie Disarmer / Objection Buster", "text": f"I can arrange a quick trial for you today. Which device are you using so I can prepare the best configuration for you?"}
5630
  ],
5631
  "model": selected_model
5632
  }
 
 
5633
  except Exception as e:
5634
- raise HTTPException(status_code=400, detail=f"AI DM analysis failed: {str(e)}")
 
5635
 
5636
  @app.delete("/api/admin/users/{user_id}")
5637
  async def admin_delete_user(user_id: str, admin_id: str = Depends(get_current_admin)):
 
5533
 
5534
  @app.post("/api/ai/analyze-dm-conversation")
5535
  async def analyze_dm_conversation(req: AIAnalyzeDmRequest, user_id: str = Depends(get_current_user_id)):
5536
+ """Analyzes a Telegram DM conversation flow and generates 3 natural, context-aware reply suggestions based on the last message."""
5537
  msgs = req.messages or []
5538
  if not msgs:
5539
  raise HTTPException(status_code=400, detail="Conversation messages are required.")
 
5541
  key = (req.api_key or "").strip()
5542
  selected_model = (req.model or "").strip() or "meta-llama/llama-3.3-70b-instruct"
5543
  if not key:
5544
+ raise HTTPException(status_code=400, detail="OpenRouter API key is required. Please click 'Connect AI' to configure your key.")
5545
 
5546
+ contact = req.contact_name or "Contact"
5547
  transcript_lines = []
5548
  for m in msgs:
5549
+ speaker = "Me (Our Account)" if m.get("is_out") else f"{contact}"
5550
  text_line = (m.get("text") or "").strip()
5551
  if text_line:
5552
  transcript_lines.append(f"{speaker}: {text_line}")
5553
  transcript = "\n".join(transcript_lines) or "No textual messages exchanged yet."
5554
 
5555
+ # Identify the last message in thread and the contact's latest statement
5556
+ last_msg = msgs[-1] if msgs else {}
5557
+ last_is_out = bool(last_msg.get("is_out"))
5558
+ last_speaker = "Me (Our Account)" if last_is_out else f"{contact}"
5559
+ last_text = (last_msg.get("text") or "").strip()
5560
+
5561
+ last_incoming_msg = next((m for m in reversed(msgs) if not m.get("is_out")), None)
5562
+ last_incoming_text = (last_incoming_msg.get("text") or "").strip() if last_incoming_msg else ""
5563
+
5564
+ if last_is_out:
5565
+ context_focus = (
5566
+ f"The latest message in the thread was sent by Me (Our Account): \"{last_text}\".\n"
5567
+ f"Prior to that, {contact}'s latest statement was: \"{last_incoming_text}\".\n"
5568
+ f"Generate 3 natural follow-up options or next conversation steps to keep things moving with {contact}."
5569
+ )
5570
+ else:
5571
+ context_focus = (
5572
+ f"The latest message is from {contact}:\n"
5573
+ f"\"{last_text}\"\n\n"
5574
+ f"Generate 3 distinct, natural Telegram replies that I can copy and send directly back to {contact} answering or reacting to their message."
5575
+ )
5576
+
5577
  prompt = (
5578
+ f"You are a skilled, friendly Telegram conversation assistant helping me chat with {contact}.\n\n"
5579
+ f"--- CONVERSATION HISTORY (Chronological) ---\n"
 
5580
  f"{transcript}\n"
5581
+ f"--------------------------------------------\n\n"
5582
+ f"{context_focus}\n\n"
5583
+ f"OBJECTIVE:\n"
5584
+ f"Carefully read the entire conversation flow above, paying closest attention to what {contact} is asking or discussing.\n"
5585
+ f"Generate 3 distinct, contextual, natural Telegram replies that I can copy and send directly back to {contact}.\n\n"
5586
+ f"RULES FOR REPLIES:\n"
5587
+ f"1. CONTEXTUAL & DIRECT: The replies MUST directly answer, acknowledge, or react to what was just said. Do NOT use canned sales pitches or assume products unless specifically discussed in the messages.\n"
5588
+ f"2. NATURAL TELEGRAM TONE: Write like a real, competent human chatting on Telegram. Friendly, direct, concise, and smooth. No robotic bullet points, no fake hype, no stiff corporate speak.\n"
5589
+ f"3. THREE DISTINCT STYLES:\n"
5590
+ f" - Option 1 (Direct & Friendly): Answers their exact point warmly and keeps the conversation flowing.\n"
5591
+ f" - Option 2 (Helpful & Informative): Provides clear, practical insight or addresses their specific query.\n"
5592
+ f" - Option 3 (Smooth Next Step): Politely guides the conversation toward a clear next step or asks a natural follow-up question.\n"
5593
+ f"4. 100% READY TO SEND: Do NOT use any placeholders like '[insert link]' or '[name]'. Write full, ready-to-copy text.\n\n"
5594
  f"Return ONLY valid JSON with this exact structure:\n"
5595
  f"{{\n"
5596
+ f' "conversation_summary": <1 sentence summarizing what the conversation is currently about>,\n'
 
 
 
5597
  f' "suggested_replies": [\n'
5598
+ f' {{"angle": "Direct & Friendly", "text": <natural Telegram reply text>}},\n'
5599
+ f' {{"angle": "Helpful & Informative", "text": <natural Telegram reply text>}},\n'
5600
+ f' {{"angle": "Smooth Next Step", "text": <natural Telegram reply text>}}\n'
5601
  f' ]\n'
5602
  f"}}"
5603
  )
 
5607
  payload: Dict[str, Any] = {
5608
  "model": selected_model,
5609
  "messages": [{"role": "user", "content": prompt}],
5610
+ "max_tokens": 2000,
5611
  "include_reasoning": False
5612
  }
5613
  if not any(om in selected_model.lower() for om in ("o1-", "o3-", "o1", "o3", "reasoner")):
5614
+ payload["temperature"] = 0.7
5615
 
5616
  res = await client.post(
5617
  "https://openrouter.ai/api/v1/chat/completions",
 
5623
  },
5624
  json=payload
5625
  )
5626
+
5627
+ if res.status_code != 200:
5628
+ err_detail = f"HTTP {res.status_code}"
5629
+ try:
5630
+ err_json = res.json()
5631
+ err_detail = err_json.get("error", {}).get("message") or res.text
5632
+ except Exception:
5633
+ err_detail = res.text[:200]
5634
+ log_debug(f"OPENROUTER_DM_ERR ({res.status_code}): {err_detail}")
5635
+ raise HTTPException(status_code=400, detail=f"OpenRouter Error ({res.status_code}): {err_detail}")
5636
+
5637
+ data = res.json()
5638
+ choices = data.get("choices") or []
5639
+ if choices:
5640
+ content = choices[0].get("message", {}).get("content") or ""
5641
+ content = re.sub(r'<think>[\s\S]*?</think>', '', content, flags=re.IGNORECASE)
5642
+ content = re.sub(r'```(?:json)?', '', content).strip('`').strip()
5643
+ s = content.find('{')
5644
+ e = content.rfind('}')
5645
+ if s != -1 and e != -1:
5646
+ parsed = json.loads(content[s:e+1])
5647
+ replies = parsed.get("suggested_replies") or []
5648
+ if replies:
5649
  return {
5650
+ "conversation_summary": parsed.get("conversation_summary") or f"Conversation with {contact}",
5651
+ "suggested_replies": replies,
 
 
 
5652
  "model": selected_model
5653
  }
5654
+
5655
+ # If JSON parsing was incomplete but content was returned
5656
  return {
5657
+ "conversation_summary": f"Discussion with {contact}",
 
 
 
5658
  "suggested_replies": [
5659
+ {"angle": "Direct Response", "text": f"Hey {contact}, thanks for following up on this! Let me know if you'd like to dive into the details."},
5660
+ {"angle": "Helpful Clarification", "text": f"Hi {contact}, happy to clarify that for you. When works best for a quick chat?"},
5661
+ {"angle": "Next Steps", "text": f"Sounds good {contact}! Let's coordinate the next step so we can get this moving."}
5662
  ],
5663
  "model": selected_model
5664
  }
5665
+ except HTTPException:
5666
+ raise
5667
  except Exception as e:
5668
+ log_debug(f"AI DM analysis failed: {str(e)}")
5669
+ raise HTTPException(status_code=400, detail=f"AI suggestion generation failed: {str(e)}")
5670
 
5671
  @app.delete("/api/admin/users/{user_id}")
5672
  async def admin_delete_user(user_id: str, admin_id: str = Depends(get_current_admin)):
frontend/src/app/ai-assistant/page.tsx CHANGED
The diff for this file is too large to render. See raw diff