|
|
""" |
|
|
CX AI Agent - Enterprise B2B Sales Intelligence Platform |
|
|
|
|
|
Automated AI-powered sales platform that: |
|
|
1. Onboards client companies and builds their knowledge base |
|
|
2. AI automatically discovers and researches prospect companies |
|
|
3. AI finds decision makers at each prospect |
|
|
4. Drafts personalized outreach emails |
|
|
5. Generates handoff packet |
|
|
s for sales teams |
|
|
6. Provides AI chat for prospect engagement |
|
|
|
|
|
Everything is AI-driven - no manual prospect entry needed. |
|
|
""" |
|
|
|
|
|
import os |
|
|
import gradio as gr |
|
|
import asyncio |
|
|
import logging |
|
|
import json |
|
|
import base64 |
|
|
from pathlib import Path |
|
|
from dotenv import load_dotenv |
|
|
from datetime import datetime |
|
|
|
|
|
|
|
|
load_dotenv() |
|
|
|
|
|
|
|
|
os.environ["USE_IN_MEMORY_MCP"] = "true" |
|
|
|
|
|
|
|
|
from mcp.registry import get_mcp_registry |
|
|
from mcp.agents.autonomous_agent_hf import AutonomousMCPAgentHF |
|
|
|
|
|
|
|
|
import io |
|
|
import sys |
|
|
|
|
|
log_capture_string = io.StringIO() |
|
|
logging.basicConfig( |
|
|
level=logging.INFO, |
|
|
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', |
|
|
handlers=[ |
|
|
logging.StreamHandler(sys.stdout), |
|
|
logging.StreamHandler(log_capture_string) |
|
|
] |
|
|
) |
|
|
logger = logging.getLogger(__name__) |
|
|
|
|
|
|
|
|
print("\n" + "="*80) |
|
|
print("π CX AI AGENT - ENTERPRISE B2B SALES INTELLIGENCE") |
|
|
print("="*80) |
|
|
|
|
|
|
|
|
|
|
|
HF_MODEL = os.getenv("HF_MODEL", "Qwen/Qwen3-32B") |
|
|
HF_PROVIDER = os.getenv("HF_PROVIDER", "nscale") |
|
|
|
|
|
session_hf_token = {"token": None} |
|
|
|
|
|
print(f"π€ AI Mode: HuggingFace Inference API") |
|
|
print(f" Model: {HF_MODEL}") |
|
|
print(f" Provider: {HF_PROVIDER}") |
|
|
print("βΉοΈ HF_TOKEN must be entered by user in the Setup tab") |
|
|
|
|
|
serper_key = os.getenv('SERPER_API_KEY') |
|
|
if serper_key: |
|
|
print(f"β
SERPER_API_KEY loaded") |
|
|
else: |
|
|
print("β οΈ SERPER_API_KEY not found - Web search limited") |
|
|
|
|
|
space_id = os.getenv('SPACE_ID') |
|
|
if space_id: |
|
|
print(f"π Running in: {space_id}") |
|
|
print("="*80 + "\n") |
|
|
|
|
|
|
|
|
try: |
|
|
mcp_registry = get_mcp_registry() |
|
|
print("β
AI Services initialized") |
|
|
except Exception as e: |
|
|
print(f"β Initialization failed: {e}") |
|
|
raise |
|
|
|
|
|
|
|
|
|
|
|
def warmup_hf_model(): |
|
|
""" |
|
|
Send a dummy prompt to warm up the HuggingFace Inference API. |
|
|
This ensures the model is loaded and ready for the first real request. |
|
|
""" |
|
|
token = session_hf_token.get("token") |
|
|
if not token: |
|
|
print("βοΈ Skipping model warm-up (token will be provided by user)") |
|
|
return |
|
|
|
|
|
try: |
|
|
import requests |
|
|
print(f"π₯ Warming up HuggingFace model ({HF_MODEL} via {HF_PROVIDER})...") |
|
|
|
|
|
headers = { |
|
|
"Authorization": f"Bearer {token}", |
|
|
"Content-Type": "application/json" |
|
|
} |
|
|
|
|
|
|
|
|
if HF_PROVIDER and HF_PROVIDER != "hf-inference": |
|
|
headers["X-HF-Provider"] = HF_PROVIDER |
|
|
|
|
|
|
|
|
response = requests.post( |
|
|
"https://router.huggingface.co/v1/chat/completions", |
|
|
headers=headers, |
|
|
json={ |
|
|
"model": HF_MODEL, |
|
|
"messages": [{"role": "user", "content": "Hello"}], |
|
|
"max_tokens": 10 |
|
|
}, |
|
|
timeout=30 |
|
|
) |
|
|
|
|
|
if response.status_code == 200: |
|
|
print(f"β
Model warmed up and ready!") |
|
|
elif response.status_code == 402: |
|
|
print(f"βΉοΈ Model {HF_MODEL} requires paid credits - will use fallback models") |
|
|
elif response.status_code == 404: |
|
|
print(f"βΉοΈ Model {HF_MODEL} not found via {HF_PROVIDER} - will try on first use") |
|
|
else: |
|
|
print(f"βΉοΈ Warm-up returned {response.status_code} - model will load on first use") |
|
|
except Exception as e: |
|
|
|
|
|
print(f"β οΈ Model warm-up skipped: {e}") |
|
|
|
|
|
|
|
|
|
|
|
def get_hf_token(ui_token: str = None) -> str: |
|
|
"""Get HF token from UI input, session storage, or environment""" |
|
|
if ui_token and ui_token.strip(): |
|
|
|
|
|
session_hf_token["token"] = ui_token.strip() |
|
|
return ui_token.strip() |
|
|
return session_hf_token.get("token") or "" |
|
|
|
|
|
|
|
|
|
|
|
session_serper_key = {"key": None} |
|
|
|
|
|
def get_serper_key(ui_key: str = None) -> str: |
|
|
"""Get SERPER API key from UI input, session storage, or environment. |
|
|
Priority: UI input > session storage > environment variable""" |
|
|
if ui_key and ui_key.strip(): |
|
|
|
|
|
session_serper_key["key"] = ui_key.strip() |
|
|
return ui_key.strip() |
|
|
if session_serper_key.get("key"): |
|
|
return session_serper_key["key"] |
|
|
|
|
|
return os.getenv('SERPER_API_KEY') or "" |
|
|
|
|
|
def update_search_service_key(): |
|
|
"""Update the search service singleton with current SERPER key""" |
|
|
from services.web_search import get_search_service |
|
|
key = get_serper_key() |
|
|
if key: |
|
|
service = get_search_service() |
|
|
service.api_key = key |
|
|
|
|
|
|
|
|
|
|
|
import threading |
|
|
warmup_thread = threading.Thread(target=warmup_hf_model, daemon=True) |
|
|
warmup_thread.start() |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
knowledge_base = { |
|
|
"client": { |
|
|
"name": None, |
|
|
"industry": None, |
|
|
"target_market": None, |
|
|
"products_services": None, |
|
|
"value_proposition": None, |
|
|
"ideal_customer_profile": None, |
|
|
"researched_at": None, |
|
|
"raw_research": None |
|
|
}, |
|
|
"prospects": [], |
|
|
"contacts": [], |
|
|
"emails": [], |
|
|
"chat_history": [], |
|
|
} |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
ENTERPRISE_CSS = """ |
|
|
/* ============== CSS VARIABLES ============== */ |
|
|
:root { |
|
|
--primary-blue: #0176D3; |
|
|
--primary-dark: #014486; |
|
|
--primary-light: #E5F3FE; |
|
|
--success-green: #2E844A; |
|
|
--success-light: #E6F4EA; |
|
|
--warning-orange: #DD7A01; |
|
|
--warning-light: #FEF3E2; |
|
|
--error-red: #EA001E; |
|
|
--error-light: #FDE7E9; |
|
|
--purple: #9050E9; |
|
|
--bg-primary: #FFFFFF; |
|
|
--bg-secondary: #F8FAFC; |
|
|
--bg-tertiary: #F1F5F9; |
|
|
--bg-hover: #E2E8F0; |
|
|
--text-primary: #1E293B; |
|
|
--text-secondary: #64748B; |
|
|
--text-tertiary: #94A3B8; |
|
|
--text-inverse: #FFFFFF; |
|
|
--border-color: #E2E8F0; |
|
|
--input-bg: #FFFFFF; |
|
|
--input-border: #CBD5E1; |
|
|
--card-shadow: 0 1px 3px rgba(0,0,0,0.1), 0 1px 2px rgba(0,0,0,0.06); |
|
|
--card-shadow-hover: 0 4px 6px rgba(0,0,0,0.1), 0 2px 4px rgba(0,0,0,0.06); |
|
|
--sidebar-width: 250px; |
|
|
--sidebar-collapsed: 64px; |
|
|
--header-height: 56px; |
|
|
} |
|
|
|
|
|
/* ============== DARK MODE ============== */ |
|
|
.dark { |
|
|
--primary-blue: #4DA6FF; |
|
|
--primary-dark: #0176D3; |
|
|
--primary-light: #1E3A5F; |
|
|
--success-green: #4ADE80; |
|
|
--success-light: #1A3A2A; |
|
|
--warning-orange: #FBBF24; |
|
|
--warning-light: #3D2E1A; |
|
|
--error-red: #F87171; |
|
|
--error-light: #3D1A1A; |
|
|
--purple: #A78BFA; |
|
|
--bg-primary: #1E293B; |
|
|
--bg-secondary: #0F172A; |
|
|
--bg-tertiary: #1E293B; |
|
|
--bg-hover: #334155; |
|
|
--text-primary: #F1F5F9; |
|
|
--text-secondary: #94A3B8; |
|
|
--text-tertiary: #64748B; |
|
|
--text-inverse: #0F172A; |
|
|
--border-color: #334155; |
|
|
--input-bg: #1E293B; |
|
|
--input-border: #475569; |
|
|
--card-shadow: 0 1px 3px rgba(0,0,0,0.3), 0 1px 2px rgba(0,0,0,0.2); |
|
|
--card-shadow-hover: 0 4px 6px rgba(0,0,0,0.3), 0 2px 4px rgba(0,0,0,0.2); |
|
|
} |
|
|
|
|
|
.dark .sidebar { |
|
|
background: linear-gradient(180deg, #0F172A 0%, #020617 100%); |
|
|
} |
|
|
|
|
|
.dark .gradio-container { |
|
|
background: var(--bg-secondary) !important; |
|
|
} |
|
|
|
|
|
/* ============== GLOBAL RESET ============== */ |
|
|
*, *::before, *::after { box-sizing: border-box !important; } |
|
|
|
|
|
/* ============== GRADIO CONTAINER RESET ============== */ |
|
|
.gradio-container { |
|
|
max-width: 100% !important; |
|
|
width: 100% !important; |
|
|
padding: 0 !important; |
|
|
margin: 0 !important; |
|
|
background: var(--bg-secondary) !important; |
|
|
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif !important; |
|
|
} |
|
|
|
|
|
/* Hide Gradio footer and unnecessary elements */ |
|
|
footer { display: none !important; } |
|
|
.gradio-container > div > div > div:first-child:empty { display: none !important; } |
|
|
|
|
|
/* ============== SIDEBAR STYLES ============== */ |
|
|
.sidebar { |
|
|
position: fixed; |
|
|
left: 0; |
|
|
top: 0; |
|
|
width: var(--sidebar-width); |
|
|
height: 100vh; |
|
|
background: linear-gradient(180deg, #1E3A5F 0%, #0F2942 100%); |
|
|
display: flex; |
|
|
flex-direction: column; |
|
|
z-index: 1000; |
|
|
transition: width 0.3s ease, transform 0.3s ease; |
|
|
overflow: hidden; |
|
|
} |
|
|
|
|
|
.sidebar.collapsed { width: var(--sidebar-collapsed); } |
|
|
|
|
|
.sidebar-header { |
|
|
padding: 16px; |
|
|
display: flex; |
|
|
align-items: center; |
|
|
gap: 12px; |
|
|
border-bottom: 1px solid rgba(255,255,255,0.1); |
|
|
height: var(--header-height); |
|
|
flex-shrink: 0; |
|
|
} |
|
|
|
|
|
.sidebar-logo { |
|
|
width: 32px; |
|
|
height: 32px; |
|
|
border-radius: 8px; |
|
|
flex-shrink: 0; |
|
|
object-fit: contain; |
|
|
} |
|
|
|
|
|
.sidebar-brand { |
|
|
color: white; |
|
|
font-weight: 700; |
|
|
font-size: 16px; |
|
|
white-space: nowrap; |
|
|
overflow: hidden; |
|
|
opacity: 1; |
|
|
transition: opacity 0.2s ease; |
|
|
} |
|
|
|
|
|
.sidebar.collapsed .sidebar-brand { opacity: 0; } |
|
|
|
|
|
.sidebar-nav { |
|
|
flex: 1; |
|
|
padding: 12px 8px; |
|
|
overflow-y: auto; |
|
|
overflow-x: hidden; |
|
|
} |
|
|
|
|
|
.nav-item { |
|
|
display: flex; |
|
|
align-items: center; |
|
|
gap: 12px; |
|
|
padding: 10px 12px; |
|
|
margin: 2px 0; |
|
|
border-radius: 8px; |
|
|
color: rgba(255,255,255,0.7); |
|
|
cursor: pointer; |
|
|
transition: all 0.15s ease; |
|
|
white-space: nowrap; |
|
|
overflow: hidden; |
|
|
} |
|
|
|
|
|
.nav-item:hover { background: rgba(255,255,255,0.1); color: white; } |
|
|
.nav-item.active { background: var(--primary-blue); color: white; font-weight: 500; } |
|
|
|
|
|
.nav-icon { font-size: 18px; width: 24px; text-align: center; flex-shrink: 0; } |
|
|
.nav-text { font-size: 14px; opacity: 1; transition: opacity 0.2s ease; } |
|
|
.sidebar.collapsed .nav-text { opacity: 0; } |
|
|
|
|
|
.toggle-btn { |
|
|
position: absolute; |
|
|
right: -14px; |
|
|
top: 70px; |
|
|
width: 28px; |
|
|
height: 28px; |
|
|
background: white; |
|
|
border: 2px solid var(--border-color); |
|
|
border-radius: 50%; |
|
|
cursor: pointer; |
|
|
display: flex; |
|
|
align-items: center; |
|
|
justify-content: center; |
|
|
font-size: 14px; |
|
|
color: var(--text-secondary); |
|
|
z-index: 1001; |
|
|
box-shadow: var(--card-shadow); |
|
|
transition: transform 0.3s ease; |
|
|
} |
|
|
|
|
|
.toggle-btn:hover { background: var(--bg-tertiary); } |
|
|
.sidebar.collapsed .toggle-btn { transform: rotate(180deg); } |
|
|
|
|
|
/* ============== MAIN CONTENT AREA ============== */ |
|
|
.main-wrapper { |
|
|
margin-left: var(--sidebar-width) !important; |
|
|
width: calc(100% - var(--sidebar-width)) !important; |
|
|
max-width: calc(100vw - var(--sidebar-width)) !important; |
|
|
min-height: 100vh; |
|
|
padding: 20px; |
|
|
transition: margin-left 0.3s ease, width 0.3s ease; |
|
|
background: var(--bg-secondary); |
|
|
overflow-x: hidden; |
|
|
box-sizing: border-box !important; |
|
|
} |
|
|
|
|
|
.main-wrapper.expanded { |
|
|
margin-left: var(--sidebar-collapsed) !important; |
|
|
width: calc(100% - var(--sidebar-collapsed)) !important; |
|
|
max-width: calc(100vw - var(--sidebar-collapsed)) !important; |
|
|
} |
|
|
|
|
|
/* Ensure Gradio's inner containers don't overflow */ |
|
|
.main-wrapper > div, |
|
|
.main-wrapper > div > div { |
|
|
max-width: 100% !important; |
|
|
overflow-x: hidden; |
|
|
} |
|
|
|
|
|
.content-area { |
|
|
max-width: 1200px; |
|
|
margin: 0 auto; |
|
|
} |
|
|
|
|
|
/* ============== PAGE SECTIONS ============== */ |
|
|
.page-section { |
|
|
display: none; |
|
|
animation: fadeIn 0.2s ease; |
|
|
} |
|
|
|
|
|
.page-section.active { display: block; } |
|
|
|
|
|
@keyframes fadeIn { |
|
|
from { opacity: 0; transform: translateY(8px); } |
|
|
to { opacity: 1; transform: translateY(0); } |
|
|
} |
|
|
|
|
|
/* ============== MOBILE STYLES ============== */ |
|
|
.mobile-header { |
|
|
display: none; |
|
|
position: fixed; |
|
|
top: 0; |
|
|
left: 0; |
|
|
right: 0; |
|
|
height: var(--header-height); |
|
|
background: linear-gradient(135deg, var(--primary-blue) 0%, var(--primary-dark) 100%); |
|
|
padding: 0 16px; |
|
|
align-items: center; |
|
|
gap: 12px; |
|
|
z-index: 999; |
|
|
box-shadow: var(--card-shadow); |
|
|
} |
|
|
|
|
|
.mobile-header .menu-btn { |
|
|
width: 36px; |
|
|
height: 36px; |
|
|
background: rgba(255,255,255,0.2); |
|
|
border: none; |
|
|
border-radius: 8px; |
|
|
color: white; |
|
|
font-size: 18px; |
|
|
cursor: pointer; |
|
|
} |
|
|
|
|
|
.mobile-header .title { color: white; font-weight: 600; font-size: 16px; } |
|
|
|
|
|
.sidebar-overlay { |
|
|
display: none; |
|
|
position: fixed; |
|
|
inset: 0; |
|
|
background: rgba(0,0,0,0.5); |
|
|
z-index: 999; |
|
|
} |
|
|
|
|
|
/* ============== MOBILE RESPONSIVE ============== */ |
|
|
@media (max-width: 768px) { |
|
|
.sidebar { |
|
|
transform: translateX(-100%); |
|
|
width: var(--sidebar-width) !important; |
|
|
} |
|
|
.sidebar.mobile-open { transform: translateX(0); } |
|
|
.sidebar.mobile-open ~ .sidebar-overlay { display: block; } |
|
|
.toggle-btn { display: none; } |
|
|
|
|
|
.mobile-header { display: flex; } |
|
|
|
|
|
.main-wrapper { |
|
|
margin-left: 0 !important; |
|
|
width: 100% !important; |
|
|
max-width: 100vw !important; |
|
|
padding: 16px; |
|
|
padding-top: calc(var(--header-height) + 16px); |
|
|
} |
|
|
} |
|
|
|
|
|
@media (max-width: 480px) { |
|
|
.main-wrapper { |
|
|
padding: 12px; |
|
|
padding-top: calc(var(--header-height) + 12px); |
|
|
width: 100% !important; |
|
|
} |
|
|
.page-header { padding: 16px; } |
|
|
.page-title { font-size: 20px; } |
|
|
} |
|
|
|
|
|
/* ============== NAVIGATION BUTTONS ROW ============== */ |
|
|
.nav-buttons-row { |
|
|
/* Hidden visually but accessible to JS for click events */ |
|
|
position: absolute; |
|
|
left: -9999px; |
|
|
top: -9999px; |
|
|
opacity: 0; |
|
|
pointer-events: none; |
|
|
gap: 8px; |
|
|
padding: 12px 16px; |
|
|
background: var(--bg-primary); |
|
|
border-radius: 12px; |
|
|
margin-bottom: 16px; |
|
|
box-shadow: var(--card-shadow); |
|
|
overflow-x: auto; |
|
|
flex-wrap: nowrap; |
|
|
-webkit-overflow-scrolling: touch; |
|
|
} |
|
|
|
|
|
.nav-buttons-row button { |
|
|
flex-shrink: 0; |
|
|
padding: 8px 14px !important; |
|
|
font-size: 13px !important; |
|
|
font-weight: 500 !important; |
|
|
border-radius: 8px !important; |
|
|
border: 1px solid var(--border-color) !important; |
|
|
background: var(--bg-secondary) !important; |
|
|
color: var(--text-primary) !important; |
|
|
transition: all 0.15s ease; |
|
|
white-space: nowrap; |
|
|
} |
|
|
|
|
|
.nav-buttons-row button:hover { |
|
|
background: var(--bg-hover) !important; |
|
|
border-color: var(--primary-blue) !important; |
|
|
} |
|
|
|
|
|
.nav-buttons-row button.active-nav-btn, |
|
|
.nav-buttons-row button:first-child { |
|
|
background: var(--primary-blue) !important; |
|
|
color: white !important; |
|
|
border-color: var(--primary-blue) !important; |
|
|
} |
|
|
|
|
|
/* Show nav buttons on mobile/tablet */ |
|
|
@media (max-width: 768px) { |
|
|
.nav-buttons-row { |
|
|
position: static; |
|
|
left: auto; |
|
|
top: auto; |
|
|
opacity: 1; |
|
|
pointer-events: auto; |
|
|
display: flex; |
|
|
} |
|
|
.nav-buttons-row button:first-child { |
|
|
background: var(--primary-blue) !important; |
|
|
color: white !important; |
|
|
} |
|
|
} |
|
|
|
|
|
/* Page visibility control - ensure JS can toggle pages */ |
|
|
[id^="page-"] { |
|
|
flex-direction: column; |
|
|
width: 100%; |
|
|
} |
|
|
[id^="page-"].hidden { |
|
|
display: none !important; |
|
|
} |
|
|
|
|
|
/* Hide pages by default using CSS class */ |
|
|
.page-hidden { |
|
|
display: none !important; |
|
|
} |
|
|
|
|
|
.setup-required { |
|
|
background: var(--warning-light); |
|
|
border: 2px solid var(--warning-orange); |
|
|
border-radius: 12px; |
|
|
padding: 16px 20px; |
|
|
margin-bottom: 20px; |
|
|
display: flex; |
|
|
align-items: center; |
|
|
gap: 12px; |
|
|
} |
|
|
|
|
|
.setup-complete { |
|
|
background: var(--success-light); |
|
|
border: 2px solid var(--success-green); |
|
|
border-radius: 12px; |
|
|
padding: 16px 20px; |
|
|
margin-bottom: 20px; |
|
|
display: flex; |
|
|
align-items: center; |
|
|
gap: 12px; |
|
|
} |
|
|
|
|
|
.stat-card { |
|
|
background: var(--bg-primary); |
|
|
border-radius: 12px; |
|
|
padding: 20px 24px; |
|
|
box-shadow: var(--card-shadow); |
|
|
border-left: 4px solid var(--primary-blue); |
|
|
transition: all 0.2s ease; |
|
|
} |
|
|
|
|
|
.stat-card:hover { box-shadow: var(--card-shadow-hover); transform: translateY(-2px); } |
|
|
.stat-card .stat-value { font-size: 28px; font-weight: 700; color: var(--text-primary); margin-bottom: 4px; } |
|
|
.stat-card .stat-label { font-size: 13px; color: var(--text-secondary); text-transform: uppercase; letter-spacing: 0.5px; } |
|
|
|
|
|
.action-card { |
|
|
background: var(--bg-primary); |
|
|
border-radius: 12px; |
|
|
padding: 24px; |
|
|
box-shadow: var(--card-shadow); |
|
|
margin-bottom: 16px; |
|
|
border: 1px solid var(--border-color); |
|
|
} |
|
|
|
|
|
.action-card h3 { margin: 0 0 12px 0; color: var(--text-primary); font-size: 18px; font-weight: 600; } |
|
|
.action-card p { margin: 0 0 16px 0; color: var(--text-secondary); font-size: 14px; line-height: 1.6; } |
|
|
|
|
|
/* ============== INFO BOX / HELP TIPS ============== */ |
|
|
.info-box { |
|
|
background: linear-gradient(135deg, var(--primary-light) 0%, #E8F4FD 100%); |
|
|
border: 1px solid var(--primary-blue); |
|
|
border-left: 4px solid var(--primary-blue); |
|
|
border-radius: 8px; |
|
|
padding: 16px 20px; |
|
|
margin-bottom: 20px; |
|
|
display: flex; |
|
|
gap: 12px; |
|
|
align-items: flex-start; |
|
|
} |
|
|
|
|
|
.info-box.tip { |
|
|
background: linear-gradient(135deg, #FEF3C7 0%, #FEF9E7 100%); |
|
|
border-color: var(--warning-orange); |
|
|
border-left-color: var(--warning-orange); |
|
|
} |
|
|
|
|
|
.info-box.success { |
|
|
background: linear-gradient(135deg, var(--success-light) 0%, #E8F8ED 100%); |
|
|
border-color: var(--success-green); |
|
|
border-left-color: var(--success-green); |
|
|
} |
|
|
|
|
|
.info-box-icon { |
|
|
font-size: 20px; |
|
|
flex-shrink: 0; |
|
|
margin-top: 2px; |
|
|
} |
|
|
|
|
|
.info-box-content { |
|
|
flex: 1; |
|
|
} |
|
|
|
|
|
.info-box-title { |
|
|
font-weight: 600; |
|
|
color: var(--text-primary); |
|
|
margin-bottom: 4px; |
|
|
font-size: 14px; |
|
|
} |
|
|
|
|
|
.info-box-text { |
|
|
color: var(--text-secondary); |
|
|
font-size: 13px; |
|
|
line-height: 1.5; |
|
|
margin: 0; |
|
|
} |
|
|
|
|
|
.info-box-text ul { |
|
|
margin: 8px 0 0 0; |
|
|
padding-left: 18px; |
|
|
} |
|
|
|
|
|
.info-box-text li { |
|
|
margin-bottom: 4px; |
|
|
} |
|
|
|
|
|
.dark .info-box { |
|
|
background: linear-gradient(135deg, rgba(1, 118, 211, 0.15) 0%, rgba(1, 118, 211, 0.08) 100%); |
|
|
} |
|
|
|
|
|
.dark .info-box.tip { |
|
|
background: linear-gradient(135deg, rgba(251, 191, 36, 0.15) 0%, rgba(251, 191, 36, 0.08) 100%); |
|
|
} |
|
|
|
|
|
.dark .info-box.success { |
|
|
background: linear-gradient(135deg, rgba(46, 132, 74, 0.15) 0%, rgba(46, 132, 74, 0.08) 100%); |
|
|
} |
|
|
|
|
|
/* Collapsible help section */ |
|
|
.help-toggle { |
|
|
background: none; |
|
|
border: none; |
|
|
color: var(--primary-blue); |
|
|
cursor: pointer; |
|
|
font-size: 13px; |
|
|
padding: 4px 8px; |
|
|
display: inline-flex; |
|
|
align-items: center; |
|
|
gap: 4px; |
|
|
margin-bottom: 8px; |
|
|
} |
|
|
|
|
|
.help-toggle:hover { |
|
|
text-decoration: underline; |
|
|
} |
|
|
|
|
|
button.primary { |
|
|
background: linear-gradient(135deg, var(--primary-blue) 0%, var(--primary-dark) 100%) !important; |
|
|
color: white !important; |
|
|
border: none !important; |
|
|
border-radius: 8px !important; |
|
|
padding: 12px 28px !important; |
|
|
font-size: 15px !important; |
|
|
font-weight: 600 !important; |
|
|
min-height: 44px !important; |
|
|
} |
|
|
|
|
|
button.secondary { |
|
|
background: var(--bg-primary) !important; |
|
|
color: var(--primary-blue) !important; |
|
|
border: 2px solid var(--primary-blue) !important; |
|
|
border-radius: 8px !important; |
|
|
padding: 8px 16px !important; |
|
|
font-weight: 600 !important; |
|
|
} |
|
|
|
|
|
button.stop { |
|
|
background: var(--error-red) !important; |
|
|
color: white !important; |
|
|
border: none !important; |
|
|
} |
|
|
|
|
|
input[type="text"], textarea { |
|
|
background: var(--input-bg) !important; |
|
|
color: var(--text-primary) !important; |
|
|
border: 2px solid var(--input-border) !important; |
|
|
border-radius: 8px !important; |
|
|
padding: 12px 16px !important; |
|
|
font-size: 15px !important; |
|
|
} |
|
|
|
|
|
.prospect-card { |
|
|
background: var(--bg-primary); |
|
|
border-radius: 12px; |
|
|
margin-bottom: 12px; |
|
|
border: 1px solid var(--border-color); |
|
|
box-shadow: var(--card-shadow); |
|
|
overflow: hidden; |
|
|
} |
|
|
|
|
|
.prospect-card-header { |
|
|
padding: 16px 20px; |
|
|
display: flex; |
|
|
justify-content: space-between; |
|
|
align-items: center; |
|
|
cursor: pointer; |
|
|
transition: background 0.2s ease; |
|
|
} |
|
|
|
|
|
.prospect-card-header:hover { background: var(--bg-hover); } |
|
|
|
|
|
.prospect-card-title { font-size: 16px; font-weight: 600; color: var(--text-primary); } |
|
|
|
|
|
.prospect-card-badge { padding: 4px 12px; border-radius: 12px; font-size: 12px; font-weight: 600; } |
|
|
.badge-new { background: var(--primary-light); color: var(--primary-blue); } |
|
|
.badge-researched { background: var(--success-light); color: var(--success-green); } |
|
|
|
|
|
.prospect-card-details { |
|
|
padding: 0 20px 20px 20px; |
|
|
border-top: 1px solid var(--border-color); |
|
|
background: var(--bg-secondary); |
|
|
} |
|
|
|
|
|
.detail-section { margin-top: 16px; } |
|
|
.detail-section h4 { font-size: 13px; font-weight: 600; color: var(--text-secondary); text-transform: uppercase; margin: 0 0 8px 0; } |
|
|
.detail-section p, .detail-section li { font-size: 14px; color: var(--text-primary); line-height: 1.6; margin: 4px 0; } |
|
|
|
|
|
.empty-state { text-align: center; padding: 60px 20px; color: var(--text-secondary); } |
|
|
.empty-state-icon { font-size: 56px; margin-bottom: 16px; opacity: 0.6; } |
|
|
.empty-state-title { font-size: 18px; font-weight: 600; color: var(--text-primary); margin-bottom: 8px; } |
|
|
.empty-state-desc { font-size: 14px; color: var(--text-secondary); } |
|
|
|
|
|
/* Progress Log Styling */ |
|
|
.progress-container { |
|
|
background: var(--bg-secondary); |
|
|
border-radius: 12px; |
|
|
padding: 16px; |
|
|
margin: 12px 0; |
|
|
border: 1px solid var(--border-color); |
|
|
} |
|
|
|
|
|
.progress-header { |
|
|
font-size: 18px; |
|
|
font-weight: 600; |
|
|
color: var(--text-primary); |
|
|
margin-bottom: 16px; |
|
|
padding-bottom: 12px; |
|
|
border-bottom: 1px solid var(--border-color); |
|
|
} |
|
|
|
|
|
.progress-section { |
|
|
background: var(--bg-tertiary); |
|
|
border-radius: 8px; |
|
|
padding: 12px 16px; |
|
|
margin: 8px 0; |
|
|
border-left: 3px solid var(--primary-blue); |
|
|
} |
|
|
|
|
|
.progress-item { |
|
|
display: flex; |
|
|
align-items: flex-start; |
|
|
gap: 10px; |
|
|
padding: 6px 0; |
|
|
font-size: 14px; |
|
|
line-height: 1.5; |
|
|
} |
|
|
|
|
|
.progress-icon { |
|
|
flex-shrink: 0; |
|
|
width: 20px; |
|
|
text-align: center; |
|
|
} |
|
|
|
|
|
.progress-text { |
|
|
flex: 1; |
|
|
color: var(--text-primary); |
|
|
} |
|
|
|
|
|
.progress-success { |
|
|
color: var(--success-green); |
|
|
font-weight: 500; |
|
|
} |
|
|
|
|
|
.progress-info { |
|
|
color: var(--primary-blue); |
|
|
} |
|
|
|
|
|
.progress-warning { |
|
|
color: var(--warning-orange); |
|
|
} |
|
|
|
|
|
.progress-detail { |
|
|
font-size: 12px; |
|
|
color: var(--text-secondary); |
|
|
margin-left: 30px; |
|
|
padding: 4px 0; |
|
|
} |
|
|
|
|
|
/* Collapsible Progress Log */ |
|
|
.progress-accordion { |
|
|
background: var(--bg-secondary); |
|
|
border-radius: 12px; |
|
|
border: 1px solid var(--border-color); |
|
|
margin: 12px 0; |
|
|
overflow: hidden; |
|
|
} |
|
|
|
|
|
.progress-accordion-header { |
|
|
display: flex; |
|
|
align-items: center; |
|
|
justify-content: space-between; |
|
|
padding: 14px 18px; |
|
|
background: linear-gradient(135deg, var(--primary-blue) 0%, var(--primary-dark) 100%); |
|
|
color: white; |
|
|
cursor: pointer; |
|
|
user-select: none; |
|
|
transition: background 0.2s ease; |
|
|
} |
|
|
|
|
|
.progress-accordion-header:hover { |
|
|
background: linear-gradient(135deg, var(--primary-dark) 0%, var(--primary-blue) 100%); |
|
|
} |
|
|
|
|
|
.progress-accordion-title { |
|
|
display: flex; |
|
|
align-items: center; |
|
|
gap: 12px; |
|
|
font-weight: 600; |
|
|
font-size: 15px; |
|
|
} |
|
|
|
|
|
.progress-accordion-toggle { |
|
|
font-size: 12px; |
|
|
opacity: 0.9; |
|
|
transition: transform 0.3s ease; |
|
|
} |
|
|
|
|
|
.progress-accordion.collapsed .progress-accordion-toggle { |
|
|
transform: rotate(-90deg); |
|
|
} |
|
|
|
|
|
.progress-accordion-body { |
|
|
max-height: 400px; |
|
|
overflow-y: auto; |
|
|
padding: 16px; |
|
|
transition: max-height 0.3s ease, padding 0.3s ease; |
|
|
} |
|
|
|
|
|
.progress-accordion.collapsed .progress-accordion-body { |
|
|
max-height: 0; |
|
|
padding: 0 16px; |
|
|
overflow: hidden; |
|
|
} |
|
|
|
|
|
/* Loading spinner */ |
|
|
.loading-spinner { |
|
|
display: inline-block; |
|
|
width: 18px; |
|
|
height: 18px; |
|
|
border: 2px solid rgba(255,255,255,0.3); |
|
|
border-radius: 50%; |
|
|
border-top-color: white; |
|
|
animation: spin 0.8s linear infinite; |
|
|
} |
|
|
|
|
|
@keyframes spin { |
|
|
to { transform: rotate(360deg); } |
|
|
} |
|
|
|
|
|
/* MCP Tool Call Badge */ |
|
|
.mcp-tool-badge { |
|
|
display: inline-flex; |
|
|
align-items: center; |
|
|
gap: 6px; |
|
|
background: linear-gradient(135deg, #6366f1 0%, #8b5cf6 100%); |
|
|
color: white; |
|
|
padding: 4px 10px; |
|
|
border-radius: 12px; |
|
|
font-size: 12px; |
|
|
font-weight: 500; |
|
|
margin-left: 8px; |
|
|
} |
|
|
|
|
|
.search-query-badge { |
|
|
display: inline-block; |
|
|
background: var(--bg-tertiary); |
|
|
color: var(--text-primary); |
|
|
padding: 4px 10px; |
|
|
border-radius: 6px; |
|
|
font-size: 12px; |
|
|
font-family: monospace; |
|
|
margin-left: 8px; |
|
|
max-width: 300px; |
|
|
overflow: hidden; |
|
|
text-overflow: ellipsis; |
|
|
white-space: nowrap; |
|
|
} |
|
|
|
|
|
.progress-step { |
|
|
display: flex; |
|
|
align-items: flex-start; |
|
|
gap: 12px; |
|
|
padding: 10px 0; |
|
|
border-bottom: 1px solid var(--border-color); |
|
|
} |
|
|
|
|
|
.progress-step:last-child { |
|
|
border-bottom: none; |
|
|
} |
|
|
|
|
|
.progress-step-icon { |
|
|
width: 28px; |
|
|
height: 28px; |
|
|
border-radius: 50%; |
|
|
display: flex; |
|
|
align-items: center; |
|
|
justify-content: center; |
|
|
font-size: 14px; |
|
|
flex-shrink: 0; |
|
|
} |
|
|
|
|
|
.progress-step-icon.loading { |
|
|
background: var(--primary-blue); |
|
|
} |
|
|
|
|
|
.progress-step-icon.success { |
|
|
background: var(--success-green); |
|
|
} |
|
|
|
|
|
.progress-step-icon.tool { |
|
|
background: linear-gradient(135deg, #6366f1 0%, #8b5cf6 100%); |
|
|
} |
|
|
|
|
|
.progress-step-icon.error { |
|
|
background: var(--error-red, #e74c3c); |
|
|
} |
|
|
|
|
|
.progress-step-icon.warning { |
|
|
background: var(--warning-orange, #f39c12); |
|
|
} |
|
|
|
|
|
.progress-step-content { |
|
|
flex: 1; |
|
|
} |
|
|
|
|
|
.progress-step-title { |
|
|
font-weight: 500; |
|
|
color: var(--text-primary); |
|
|
font-size: 14px; |
|
|
} |
|
|
|
|
|
.progress-step-detail { |
|
|
font-size: 12px; |
|
|
color: var(--text-secondary); |
|
|
margin-top: 2px; |
|
|
} |
|
|
|
|
|
.progress-summary { |
|
|
background: linear-gradient(135deg, var(--primary-blue) 0%, var(--primary-dark) 100%); |
|
|
color: white; |
|
|
border-radius: 8px; |
|
|
padding: 16px; |
|
|
margin-top: 16px; |
|
|
} |
|
|
|
|
|
.progress-summary h3 { |
|
|
margin: 0 0 12px 0; |
|
|
font-size: 16px; |
|
|
} |
|
|
|
|
|
.progress-summary table { |
|
|
width: 100%; |
|
|
border-collapse: collapse; |
|
|
} |
|
|
|
|
|
.progress-summary td { |
|
|
padding: 6px 8px; |
|
|
border-bottom: 1px solid rgba(255,255,255,0.2); |
|
|
} |
|
|
|
|
|
.progress-summary td:first-child { |
|
|
font-weight: 500; |
|
|
} |
|
|
|
|
|
.progress-summary td:last-child { |
|
|
text-align: right; |
|
|
font-weight: 600; |
|
|
} |
|
|
|
|
|
.footer { text-align: center; padding: 24px; color: var(--text-secondary); border-top: 1px solid var(--border-color); margin-top: 32px; } |
|
|
|
|
|
.prose { max-width: none !important; } |
|
|
.prose code { background: var(--bg-tertiary) !important; padding: 2px 6px !important; border-radius: 4px !important; } |
|
|
.prose pre { background: var(--bg-tertiary) !important; border-radius: 8px !important; padding: 16px !important; } |
|
|
|
|
|
.dark input, .dark textarea { |
|
|
background: var(--input-bg) !important; |
|
|
color: var(--text-primary) !important; |
|
|
border-color: var(--input-border) !important; |
|
|
} |
|
|
.dark label, .dark .prose, .dark .prose p { color: var(--text-primary) !important; } |
|
|
.dark .page-header, .dark .action-card, .dark .form-section, .dark .stat-card { |
|
|
background: var(--bg-primary) !important; |
|
|
} |
|
|
|
|
|
/* ============== COMPONENT RESPONSIVE STYLES ============== */ |
|
|
|
|
|
/* Stats grid */ |
|
|
.stats-grid { |
|
|
display: grid; |
|
|
grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); |
|
|
gap: 16px; |
|
|
margin-bottom: 20px; |
|
|
} |
|
|
|
|
|
/* Content grid for two-column layouts */ |
|
|
.content-grid { |
|
|
display: grid; |
|
|
grid-template-columns: 1fr 2fr; |
|
|
gap: 20px; |
|
|
} |
|
|
|
|
|
@media (max-width: 900px) { |
|
|
.content-grid { |
|
|
grid-template-columns: 1fr; |
|
|
} |
|
|
} |
|
|
|
|
|
/* Form layouts */ |
|
|
.form-section { |
|
|
background: var(--bg-primary); |
|
|
border-radius: 12px; |
|
|
padding: 20px; |
|
|
box-shadow: var(--card-shadow); |
|
|
margin-bottom: 16px; |
|
|
} |
|
|
|
|
|
/* Chatbot adjustments */ |
|
|
.chatbot, [class*="chatbot"] { |
|
|
height: 400px !important; |
|
|
border-radius: 12px !important; |
|
|
} |
|
|
|
|
|
@media (max-width: 768px) { |
|
|
.chatbot, [class*="chatbot"] { |
|
|
height: 300px !important; |
|
|
} |
|
|
|
|
|
.stats-grid { |
|
|
grid-template-columns: repeat(2, 1fr); |
|
|
gap: 12px; |
|
|
} |
|
|
|
|
|
.stat-card { |
|
|
padding: 12px !important; |
|
|
} |
|
|
|
|
|
.stat-value { font-size: 20px !important; } |
|
|
.stat-label { font-size: 10px !important; } |
|
|
|
|
|
.action-card { |
|
|
padding: 16px !important; |
|
|
} |
|
|
|
|
|
.action-card h3 { font-size: 16px !important; } |
|
|
} |
|
|
|
|
|
@media (max-width: 480px) { |
|
|
.stats-grid { |
|
|
grid-template-columns: 1fr 1fr; |
|
|
gap: 8px; |
|
|
} |
|
|
|
|
|
.chatbot, [class*="chatbot"] { |
|
|
height: 250px !important; |
|
|
} |
|
|
} |
|
|
|
|
|
/* Print styles */ |
|
|
@media print { |
|
|
.sidebar, .mobile-header, .sidebar-overlay { display: none !important; } |
|
|
.main-wrapper { margin-left: 0 !important; } |
|
|
} |
|
|
""" |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def get_stat_html(value: str, label: str, color: str) -> str: |
|
|
return f""" |
|
|
<div class="stat-card" style="border-left-color: {color};"> |
|
|
<div class="stat-value">{value}</div> |
|
|
<div class="stat-label">{label}</div> |
|
|
</div> |
|
|
""" |
|
|
|
|
|
|
|
|
def get_client_status_html() -> str: |
|
|
if knowledge_base["client"]["name"]: |
|
|
return f""" |
|
|
<div class="setup-complete"> |
|
|
<span style="font-size: 24px;">β
</span> |
|
|
<div> |
|
|
<strong style="color: var(--success-green);">Client Profile Active</strong> |
|
|
<p style="margin: 4px 0 0 0; font-size: 13px; color: var(--text-secondary);"> |
|
|
AI is finding prospects for <strong>{knowledge_base["client"]["name"]}</strong> |
|
|
</p> |
|
|
</div> |
|
|
</div> |
|
|
""" |
|
|
return """ |
|
|
<div class="setup-required"> |
|
|
<span style="font-size: 24px;">β οΈ</span> |
|
|
<div> |
|
|
<strong style="color: var(--warning-orange);">Setup Required</strong> |
|
|
<p style="margin: 4px 0 0 0; font-size: 13px; color: var(--text-secondary);"> |
|
|
Go to <strong>Setup</strong> tab to enter your company name and start AI prospect discovery. |
|
|
</p> |
|
|
</div> |
|
|
</div> |
|
|
""" |
|
|
|
|
|
|
|
|
def get_dashboard_stats(): |
|
|
return ( |
|
|
get_stat_html(str(len(knowledge_base["prospects"])), "Prospects Found", "var(--primary-blue)"), |
|
|
get_stat_html(str(len(knowledge_base["contacts"])), "Decision Makers", "var(--success-green)"), |
|
|
get_stat_html(str(len(knowledge_base["emails"])), "Emails Drafted", "var(--warning-orange)"), |
|
|
get_client_status_html() |
|
|
) |
|
|
|
|
|
|
|
|
def merge_to_knowledge_base(prospects_found: list, contacts_found: list, emails_drafted: list): |
|
|
"""Merge found data to knowledge base with deduplication""" |
|
|
global knowledge_base |
|
|
|
|
|
|
|
|
existing_prospect_keys = set() |
|
|
for p in knowledge_base["prospects"]: |
|
|
key = (p.get("name", "").lower(), p.get("domain", "").lower()) |
|
|
existing_prospect_keys.add(key) |
|
|
|
|
|
for p in prospects_found: |
|
|
key = (p.get("name", "").lower(), p.get("domain", "").lower()) |
|
|
if key not in existing_prospect_keys: |
|
|
knowledge_base["prospects"].append(p) |
|
|
existing_prospect_keys.add(key) |
|
|
|
|
|
|
|
|
existing_emails = set(c.get("email", "").lower() for c in knowledge_base["contacts"]) |
|
|
for c in contacts_found: |
|
|
email = c.get("email", "").lower() |
|
|
if email and email not in existing_emails: |
|
|
knowledge_base["contacts"].append(c) |
|
|
existing_emails.add(email) |
|
|
|
|
|
|
|
|
existing_email_keys = set() |
|
|
for e in knowledge_base["emails"]: |
|
|
key = (e.get("to", "").lower(), e.get("subject", "").lower()) |
|
|
existing_email_keys.add(key) |
|
|
|
|
|
for e in emails_drafted: |
|
|
key = (e.get("to", "").lower(), e.get("subject", "").lower()) |
|
|
if key not in existing_email_keys: |
|
|
knowledge_base["emails"].append(e) |
|
|
existing_email_keys.add(key) |
|
|
|
|
|
|
|
|
def get_prospects_html() -> str: |
|
|
if not knowledge_base["prospects"]: |
|
|
return """ |
|
|
<div class="empty-state"> |
|
|
<div class="empty-state-icon">π―</div> |
|
|
<div class="empty-state-title">No prospects discovered yet</div> |
|
|
<div class="empty-state-desc">Complete the Setup and click "Find Prospects" to let AI discover potential customers</div> |
|
|
</div> |
|
|
""" |
|
|
|
|
|
html = "" |
|
|
for p in reversed(knowledge_base["prospects"]): |
|
|
status_class = "badge-researched" if p.get("research_complete") else "badge-new" |
|
|
status_text = "RESEARCHED" if p.get("research_complete") else "DISCOVERED" |
|
|
|
|
|
|
|
|
contacts_html = "" |
|
|
p_name_lower = p.get("name", "").lower() |
|
|
prospect_contacts = [c for c in knowledge_base["contacts"] |
|
|
if p_name_lower in c.get("company", "").lower() |
|
|
or c.get("company", "").lower() in p_name_lower] |
|
|
if prospect_contacts: |
|
|
contacts_html = "<ul style='margin: 0; padding-left: 20px;'>" |
|
|
for c in prospect_contacts: |
|
|
contacts_html += f"<li><strong>{c.get('name', 'Unknown')}</strong> - {c.get('title', 'Unknown')}" |
|
|
if c.get('email'): |
|
|
contacts_html += f" ({c.get('email')})" |
|
|
contacts_html += "</li>" |
|
|
contacts_html += "</ul>" |
|
|
else: |
|
|
contacts_html = "<p style='color: var(--text-secondary);'>No contacts found yet</p>" |
|
|
|
|
|
html += f""" |
|
|
<details class="prospect-card"> |
|
|
<summary class="prospect-card-header"> |
|
|
<span class="prospect-card-title">π’ {p.get("name", "Unknown")}</span> |
|
|
<span class="prospect-card-badge {status_class}">{status_text}</span> |
|
|
</summary> |
|
|
<div class="prospect-card-details"> |
|
|
<div class="detail-section"> |
|
|
<h4>π Company Summary</h4> |
|
|
<p>{p.get("summary", "No summary available")}</p> |
|
|
</div> |
|
|
<div class="detail-section"> |
|
|
<h4>π Industry</h4> |
|
|
<p>{p.get("industry") or "Technology & Services"}</p> |
|
|
</div> |
|
|
<div class="detail-section"> |
|
|
<h4>π― Why They're a Good Fit</h4> |
|
|
<p>{p.get("fit_reason", "Matches target customer profile")}</p> |
|
|
</div> |
|
|
<div class="detail-section"> |
|
|
<h4>π₯ Decision Makers ({len(prospect_contacts)})</h4> |
|
|
{contacts_html} |
|
|
</div> |
|
|
<div class="detail-section"> |
|
|
<h4>βοΈ Outreach Status</h4> |
|
|
<p>{'β
Email drafted' if p.get("email_drafted") else 'β³ Pending'}</p> |
|
|
</div> |
|
|
<div class="detail-section"> |
|
|
<h4>π
Discovered</h4> |
|
|
<p>{p.get("discovered_at") or datetime.now().strftime("%Y-%m-%d %H:%M")}</p> |
|
|
</div> |
|
|
</div> |
|
|
</details> |
|
|
""" |
|
|
|
|
|
return html |
|
|
|
|
|
|
|
|
def get_emails_html() -> str: |
|
|
if not knowledge_base["emails"]: |
|
|
return """ |
|
|
<div class="empty-state"> |
|
|
<div class="empty-state-icon">βοΈ</div> |
|
|
<div class="empty-state-title">No emails drafted yet</div> |
|
|
<div class="empty-state-desc">AI will draft personalized emails after discovering prospects</div> |
|
|
</div> |
|
|
""" |
|
|
|
|
|
html = "" |
|
|
for e in reversed(knowledge_base["emails"]): |
|
|
body_display = e.get("body", "").replace("\n", "<br>") |
|
|
html += f""" |
|
|
<details class="prospect-card"> |
|
|
<summary class="prospect-card-header"> |
|
|
<span class="prospect-card-title">βοΈ {e.get("subject", "No subject")[:50]}{'...' if len(e.get("subject", "")) > 50 else ''}</span> |
|
|
<span class="prospect-card-badge badge-new">DRAFT</span> |
|
|
</summary> |
|
|
<div class="prospect-card-details"> |
|
|
<div class="detail-section"> |
|
|
<h4>π’ Prospect</h4> |
|
|
<p>{e.get("prospect_company", "Unknown")}</p> |
|
|
</div> |
|
|
<div class="detail-section"> |
|
|
<h4>π§ To</h4> |
|
|
<p>{e.get("to", "Not specified")}</p> |
|
|
</div> |
|
|
<div class="detail-section"> |
|
|
<h4>π Subject</h4> |
|
|
<p><strong>{e.get("subject", "No subject")}</strong></p> |
|
|
</div> |
|
|
<div class="detail-section"> |
|
|
<h4>π Email Body</h4> |
|
|
<div style="background: var(--bg-tertiary); padding: 16px; border-radius: 8px; margin-top: 8px;"> |
|
|
<p style="white-space: pre-wrap; margin: 0;">{body_display}</p> |
|
|
</div> |
|
|
</div> |
|
|
</div> |
|
|
</details> |
|
|
""" |
|
|
return html |
|
|
|
|
|
|
|
|
def get_contacts_html() -> str: |
|
|
if not knowledge_base["contacts"]: |
|
|
return """ |
|
|
<div class="empty-state"> |
|
|
<div class="empty-state-icon">π₯</div> |
|
|
<div class="empty-state-title">No contacts found yet</div> |
|
|
<div class="empty-state-desc">AI will find decision makers when discovering prospects</div> |
|
|
</div> |
|
|
""" |
|
|
|
|
|
html = """ |
|
|
<div style="background: var(--success-bg, #d4edda); border: 1px solid var(--success-border, #c3e6cb); border-radius: 8px; padding: 12px 16px; margin-bottom: 16px;"> |
|
|
<div style="font-size: 13px; color: var(--success-text, #155724);"> |
|
|
<strong>β
Verified Contacts:</strong> All contacts shown here were found through web searches of LinkedIn profiles, |
|
|
company team pages, and public directories. Only contacts with <strong>verified email addresses</strong> found on the web are displayed. |
|
|
</div> |
|
|
</div> |
|
|
""" |
|
|
for c in reversed(knowledge_base["contacts"]): |
|
|
source = c.get("source", "web_search") |
|
|
source_label = { |
|
|
"web_search": "Found via web search", |
|
|
"linkedin": "Found via LinkedIn", |
|
|
"team_page": "Found on company page", |
|
|
"web_search_and_scraping": "Verified from web" |
|
|
}.get(source, "Verified") |
|
|
html += f""" |
|
|
<div class="prospect-card" style="padding: 16px 20px;"> |
|
|
<div style="display: flex; justify-content: space-between; align-items: center;"> |
|
|
<div> |
|
|
<div style="font-weight: 600; color: var(--text-primary);">π€ {c.get("name", "Unknown")}</div> |
|
|
<div style="font-size: 13px; color: var(--text-secondary); margin-top: 4px;">{c.get("title", "Unknown title")}</div> |
|
|
<div style="font-size: 13px; color: var(--text-secondary);">π’ {c.get("company", "Unknown company")}</div> |
|
|
{f'<div style="font-size: 13px; color: var(--primary-blue); margin-top: 4px;">π§ {c.get("email")}</div>' if c.get("email") else ''} |
|
|
</div> |
|
|
<span class="prospect-card-badge badge-engaged">VERIFIED</span> |
|
|
</div> |
|
|
<div style="font-size: 11px; color: var(--text-secondary); margin-top: 8px;">{source_label}</div> |
|
|
</div> |
|
|
""" |
|
|
return html |
|
|
|
|
|
|
|
|
def reset_all_data(): |
|
|
global knowledge_base |
|
|
knowledge_base = { |
|
|
"client": {"name": None, "industry": None, "target_market": None, "products_services": None, |
|
|
"value_proposition": None, "ideal_customer_profile": None, "researched_at": None, "raw_research": None}, |
|
|
"prospects": [], "contacts": [], "emails": [], "chat_history": [] |
|
|
} |
|
|
stats = get_dashboard_stats() |
|
|
return (stats[0], stats[1], stats[2], stats[3], get_prospects_html(), get_emails_html(), |
|
|
get_contacts_html(), "", "*Enter your company name to begin.*", "*Click 'Find Prospects' after setup.*") |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
async def setup_client_company(company_name: str, hf_token_input: str, serper_key_input: str = "", progress=gr.Progress()): |
|
|
global knowledge_base |
|
|
|
|
|
if not company_name or not company_name.strip(): |
|
|
yield "β οΈ Please enter your company name." |
|
|
return |
|
|
|
|
|
|
|
|
token = get_hf_token(hf_token_input) |
|
|
if not token: |
|
|
yield "β οΈ **HF_TOKEN Required**: Please enter your HuggingFace token in the Setup tab.\n\nGet a free token at: https://huggingface.co/settings/tokens" |
|
|
return |
|
|
|
|
|
|
|
|
if serper_key_input and serper_key_input.strip(): |
|
|
get_serper_key(serper_key_input) |
|
|
|
|
|
update_search_service_key() |
|
|
|
|
|
company_name = company_name.strip() |
|
|
|
|
|
|
|
|
output = f"""<div class="progress-container"> |
|
|
<div class="progress-header">π’ Setting Up: {company_name}</div> |
|
|
<div class="progress-section"> |
|
|
<div class="progress-item"><span class="progress-icon">β³</span><span class="progress-text">Building knowledge base...</span></div> |
|
|
""" |
|
|
yield output |
|
|
progress(0.1, desc="Initializing...") |
|
|
|
|
|
try: |
|
|
|
|
|
agent = AutonomousMCPAgentHF( |
|
|
mcp_registry=mcp_registry, |
|
|
hf_token=token, |
|
|
provider=HF_PROVIDER, |
|
|
model=HF_MODEL |
|
|
) |
|
|
output += f"""<div class="progress-item"><span class="progress-icon">β
</span><span class="progress-text progress-success">AI Agent initialized ({agent.model})</span></div> |
|
|
""" |
|
|
yield output |
|
|
progress(0.2) |
|
|
except Exception as e: |
|
|
yield f"""<div class="progress-item"><span class="progress-icon">β</span><span class="progress-text" style="color: var(--error-red);">Agent init failed: {e}</span></div></div></div>""" |
|
|
return |
|
|
|
|
|
task = f"""Research {company_name} to understand their business. Use search_web to find information about: |
|
|
1. What {company_name} does - their products/services |
|
|
2. Their target market and ideal customers |
|
|
3. Their industry and market position |
|
|
4. Their value proposition |
|
|
5. What type of companies would be good prospects for them |
|
|
|
|
|
Use the save_company tool to save information about {company_name}: |
|
|
- company_id: "{company_name.lower().replace(' ', '_')}" |
|
|
- name: "{company_name}" |
|
|
- domain: their website domain |
|
|
- industry: their industry |
|
|
- description: brief company description |
|
|
|
|
|
After researching, provide a comprehensive summary of: |
|
|
- What {company_name} does |
|
|
- Who their ideal customers are |
|
|
- What industries/company types would benefit from their services |
|
|
|
|
|
This is OUR company - we need this information to find matching prospects.""" |
|
|
|
|
|
last_research = "" |
|
|
search_results_summary = [] |
|
|
search_count = 0 |
|
|
try: |
|
|
async for event in agent.run(task, max_iterations=12): |
|
|
event_type = event.get("type") |
|
|
if event_type == "model_loaded": |
|
|
output += f"""<div class="progress-item"><span class="progress-icon">π§ </span><span class="progress-text">{event.get('message', 'Model loaded')}</span></div> |
|
|
""" |
|
|
yield output |
|
|
elif event_type == "iteration_start": |
|
|
output += f"""<div class="progress-item"><span class="progress-icon">π</span><span class="progress-text progress-info">{event.get('message', 'Thinking...')}</span></div> |
|
|
""" |
|
|
yield output |
|
|
elif event_type == "tool_call": |
|
|
tool = event.get("tool", "") |
|
|
if tool == "search_web": |
|
|
output += f"""<div class="progress-item"><span class="progress-icon">π</span><span class="progress-text">Searching for {company_name}...</span></div> |
|
|
""" |
|
|
search_count += 1 |
|
|
elif tool == "search_news": |
|
|
output += f"""<div class="progress-item"><span class="progress-icon">π°</span><span class="progress-text">Finding news...</span></div> |
|
|
""" |
|
|
elif tool in ["save_company", "save_fact"]: |
|
|
output += f"""<div class="progress-item"><span class="progress-icon">πΎ</span><span class="progress-text">Saving information...</span></div> |
|
|
""" |
|
|
yield output |
|
|
progress(0.3 + min(search_count * 0.1, 0.4)) |
|
|
elif event_type == "tool_result": |
|
|
tool = event.get("tool", "") |
|
|
result = event.get("result", {}) |
|
|
if tool in ["search_web", "search_news"]: |
|
|
count = result.get("count", 0) if isinstance(result, dict) else 0 |
|
|
output += f"""<div class="progress-detail">β
Found {count} results</div> |
|
|
""" |
|
|
|
|
|
if isinstance(result, dict) and result.get("results"): |
|
|
for r in result.get("results", [])[:3]: |
|
|
if isinstance(r, dict): |
|
|
title = r.get("title", "") |
|
|
|
|
|
snippet = r.get("body", r.get("text", r.get("snippet", r.get("description", "")))) |
|
|
if title and title not in str(search_results_summary): |
|
|
if snippet: |
|
|
search_results_summary.append(f"- **{title}**: {snippet[:200]}..." if len(snippet) > 200 else f"- **{title}**: {snippet}") |
|
|
else: |
|
|
search_results_summary.append(f"- **{title}**") |
|
|
yield output |
|
|
elif event_type == "thought": |
|
|
|
|
|
thought = event.get("thought", "") |
|
|
message = event.get("message", "") |
|
|
|
|
|
if thought and not thought.startswith("CX AI Agent") and "Powered by AI" not in thought and not thought.startswith("[Processing:"): |
|
|
if len(thought) > len(last_research): |
|
|
last_research = thought |
|
|
logger.info(f"Captured research thought: {thought[:100]}...") |
|
|
|
|
|
output += f"π {message}\n" |
|
|
yield output |
|
|
elif message: |
|
|
|
|
|
output += f"π€ {message}\n" |
|
|
yield output |
|
|
elif event_type == "agent_complete": |
|
|
final_answer = event.get("final_answer", "") |
|
|
|
|
|
if not final_answer or "CX AI Agent" in final_answer or "Powered by AI" in final_answer: |
|
|
final_answer = last_research |
|
|
|
|
|
if not final_answer and search_results_summary: |
|
|
final_answer = f"**{company_name}** - Research findings:\n\n" + "\n".join(search_results_summary[:10]) |
|
|
if not final_answer: |
|
|
final_answer = f"Research completed for {company_name}. The AI gathered information about the company. Ready to find prospects." |
|
|
knowledge_base["client"] = { |
|
|
"name": company_name, |
|
|
"raw_research": final_answer, |
|
|
"researched_at": datetime.now().strftime("%Y-%m-%d %H:%M") |
|
|
} |
|
|
output += f"\n---\n\n## β
{company_name} Profile Complete!\n\n" |
|
|
output += "**Next step:** Go to the **Discovery** tab and click **'π Find Prospects & Contacts'** to let AI discover potential customers.\n\n" |
|
|
|
|
|
|
|
|
if search_results_summary: |
|
|
output += "---\n\n### π Search Results Found\n\n" |
|
|
output += "\n".join(search_results_summary[:8]) |
|
|
output += "\n\n" |
|
|
|
|
|
output += f"---\n\n### π Research Summary\n\n{final_answer}" |
|
|
yield output |
|
|
progress(1.0) |
|
|
return |
|
|
elif event_type == "agent_max_iterations": |
|
|
|
|
|
final_answer = last_research |
|
|
if not final_answer and search_results_summary: |
|
|
final_answer = f"**{company_name}** - Research findings:\n\n" + "\n".join(search_results_summary[:10]) |
|
|
if not final_answer: |
|
|
final_answer = f"Research completed for {company_name}. Ready to find prospects." |
|
|
knowledge_base["client"] = { |
|
|
"name": company_name, |
|
|
"raw_research": final_answer, |
|
|
"researched_at": datetime.now().strftime("%Y-%m-%d %H:%M") |
|
|
} |
|
|
output += f"\n---\n\n## β
{company_name} Profile Complete!\n\n" |
|
|
output += "**Next step:** Go to the **Discovery** tab and click **'π Find Prospects & Contacts'** to let AI discover potential customers.\n\n" |
|
|
if final_answer: |
|
|
output += f"---\n\n### π Research Summary\n\n{final_answer}" |
|
|
yield output |
|
|
progress(1.0) |
|
|
return |
|
|
elif event_type == "agent_error": |
|
|
error_msg = event.get("error", "Unknown error") |
|
|
|
|
|
knowledge_base["client"] = { |
|
|
"name": company_name, |
|
|
"raw_research": last_research or f"{company_name} - manual research may be needed.", |
|
|
"researched_at": datetime.now().strftime("%Y-%m-%d %H:%M") |
|
|
} |
|
|
output += f"\nβ οΈ AI encountered an issue: {error_msg}\n" |
|
|
output += f"\n---\n\n## β οΈ {company_name} Setup (Partial)\n\n" |
|
|
output += "**Note:** Some research may be incomplete. You can still proceed to find prospects.\n\n" |
|
|
yield output |
|
|
progress(1.0) |
|
|
return |
|
|
except Exception as e: |
|
|
|
|
|
knowledge_base["client"] = { |
|
|
"name": company_name, |
|
|
"raw_research": last_research or f"{company_name} - setup interrupted.", |
|
|
"researched_at": datetime.now().strftime("%Y-%m-%d %H:%M") |
|
|
} |
|
|
output += f"\nβ οΈ Error: {e}\n" |
|
|
output += f"\n**Note:** Basic profile saved. You can still try to find prospects.\n" |
|
|
yield output |
|
|
return |
|
|
|
|
|
|
|
|
|
|
|
if not knowledge_base["client"]["name"]: |
|
|
final_answer = last_research |
|
|
if not final_answer and search_results_summary: |
|
|
final_answer = f"**{company_name}** - Research findings:\n\n" + "\n".join(search_results_summary[:10]) |
|
|
if not final_answer: |
|
|
final_answer = f"Research completed for {company_name}. Ready to find prospects." |
|
|
knowledge_base["client"] = { |
|
|
"name": company_name, |
|
|
"raw_research": final_answer, |
|
|
"researched_at": datetime.now().strftime("%Y-%m-%d %H:%M") |
|
|
} |
|
|
output += f"\n---\n\n## β
{company_name} Profile Complete!\n\n" |
|
|
output += "**Next step:** Go to the **Discovery** tab and click **'π Find Prospects & Contacts'** to let AI discover potential customers.\n\n" |
|
|
output += f"---\n\n### π Research Summary\n\n{final_answer}" |
|
|
yield output |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
async def discover_prospects(num_prospects: int, progress=gr.Progress()): |
|
|
global knowledge_base |
|
|
|
|
|
if not knowledge_base["client"]["name"]: |
|
|
yield "β οΈ **Setup Required**: Please go to Setup tab and enter your company name first." |
|
|
return |
|
|
|
|
|
|
|
|
token = session_hf_token.get("token") |
|
|
if not token: |
|
|
yield "β οΈ **HF_TOKEN Required**: Please enter your HuggingFace token in the **Setup** tab first.\n\nGet a free token at: https://huggingface.co/settings/tokens" |
|
|
return |
|
|
|
|
|
|
|
|
update_search_service_key() |
|
|
|
|
|
client_name = knowledge_base["client"]["name"] |
|
|
client_info = knowledge_base["client"].get("raw_research", "") |
|
|
|
|
|
|
|
|
progress_steps = [] |
|
|
|
|
|
def build_accordion(steps, is_loading=True, summary_html=""): |
|
|
"""Build the collapsible accordion HTML""" |
|
|
status_text = "Processing..." if is_loading else "Complete" |
|
|
spinner = '<div class="loading-spinner"></div>' if is_loading else 'β
' |
|
|
|
|
|
steps_html = "" |
|
|
for step in steps: |
|
|
icon_class = step.get("icon_class", "tool") |
|
|
steps_html += f'''<div class="progress-step"> |
|
|
<div class="progress-step-icon {icon_class}">{step.get("icon", "π§")}</div> |
|
|
<div class="progress-step-content"> |
|
|
<div class="progress-step-title">{step.get("title", "")}</div> |
|
|
{f'<div class="progress-step-detail">{step.get("detail", "")}</div>' if step.get("detail") else ""} |
|
|
</div> |
|
|
</div>''' |
|
|
|
|
|
return f'''<div class="progress-accordion" id="discovery-progress"> |
|
|
<div class="progress-accordion-header" onclick="this.parentElement.classList.toggle('collapsed')"> |
|
|
<div class="progress-accordion-title"> |
|
|
{spinner} |
|
|
<span>π AI Discovery Progress - {status_text}</span> |
|
|
</div> |
|
|
<span class="progress-accordion-toggle">βΌ</span> |
|
|
</div> |
|
|
<div class="progress-accordion-body"> |
|
|
{steps_html} |
|
|
</div> |
|
|
</div> |
|
|
{summary_html}''' |
|
|
|
|
|
progress_steps.append({"icon": "β³", "icon_class": "loading", "title": "Initializing AI agent...", "detail": f"Preparing to find prospects for {client_name}"}) |
|
|
yield build_accordion(progress_steps) |
|
|
progress(0.1) |
|
|
|
|
|
try: |
|
|
|
|
|
agent = AutonomousMCPAgentHF( |
|
|
mcp_registry=mcp_registry, |
|
|
hf_token=token, |
|
|
provider=HF_PROVIDER, |
|
|
model=HF_MODEL |
|
|
) |
|
|
progress_steps[-1] = {"icon": "β
", "icon_class": "success", "title": "AI Agent initialized", "detail": f"Model: {agent.model}"} |
|
|
yield build_accordion(progress_steps) |
|
|
progress(0.2) |
|
|
except Exception as e: |
|
|
progress_steps[-1] = {"icon": "β", "icon_class": "error", "title": "Agent initialization failed", "detail": str(e)[:100]} |
|
|
yield build_accordion(progress_steps, is_loading=False) |
|
|
return |
|
|
|
|
|
|
|
|
|
|
|
client_industry_desc = f"{client_name}" |
|
|
if client_info: |
|
|
|
|
|
info_snippet = client_info[:300].split('.')[0] if '.' in client_info[:300] else client_info[:200] |
|
|
client_industry_desc = f"{client_name} - {info_snippet}" |
|
|
|
|
|
task = f"""You are an AI sales agent finding prospects for {client_name}. |
|
|
|
|
|
About {client_name}: |
|
|
{client_info} |
|
|
|
|
|
USE THE discover_prospects_with_contacts TOOL - it handles everything automatically: |
|
|
- Searches for potential prospect companies (CUSTOMERS who would buy from {client_name}) |
|
|
- Finds verified contacts for each (LinkedIn, company websites, directories, etc.) |
|
|
- ONLY saves prospects that have real verified contacts |
|
|
- Keeps searching until target is met or max attempts reached |
|
|
- Skips companies without contacts automatically |
|
|
|
|
|
STEP 1: Call discover_prospects_with_contacts with accurate industry description: |
|
|
{{"client_company": "{client_name}", "client_industry": "{client_industry_desc}", "target_prospects": {num_prospects}, "target_titles": ["CEO", "Founder", "VP Sales", "CTO", "Head of Sales"]}} |
|
|
|
|
|
STEP 2: After discovery completes, for each prospect with contacts, draft personalized email: |
|
|
- Use send_email tool with the REAL contact info returned |
|
|
- to: actual verified email |
|
|
- subject: Reference {client_name} AND the prospect's business |
|
|
- body: Personalized email mentioning the contact by name and specific facts about their company |
|
|
- prospect_id: the prospect_id from discovery results |
|
|
|
|
|
IMPORTANT: |
|
|
- The discover_prospects_with_contacts tool does ALL the hard work |
|
|
- It will check multiple companies until it finds {num_prospects} with verified contacts |
|
|
- Only prospects WITH contacts are saved (no useless data) |
|
|
- NEVER invent contact names or emails - only use what the tool returns |
|
|
|
|
|
After the tool completes, provide a summary of: |
|
|
- Prospects saved (with verified contacts) |
|
|
- Total contacts found |
|
|
- Companies checked vs skipped |
|
|
- Emails drafted""" |
|
|
|
|
|
prospects_found = [] |
|
|
contacts_found = [] |
|
|
emails_drafted = [] |
|
|
search_results_for_prospects = [] |
|
|
|
|
|
|
|
|
pending_prospect = None |
|
|
pending_contact = None |
|
|
current_prospect_name = None |
|
|
|
|
|
try: |
|
|
iteration = 0 |
|
|
last_final_answer = "" |
|
|
async for event in agent.run(task, max_iterations=25): |
|
|
event_type = event.get("type") |
|
|
iteration += 1 |
|
|
progress_pct = min(0.2 + (iteration * 0.03), 0.95) |
|
|
|
|
|
if event_type == "model_loaded": |
|
|
progress_steps.append({"icon": "π§ ", "icon_class": "success", "title": event.get('message', 'Model loaded'), "detail": ""}) |
|
|
yield build_accordion(progress_steps) |
|
|
elif event_type == "iteration_start": |
|
|
progress_steps.append({"icon": "π", "icon_class": "loading", "title": "AI is thinking...", "detail": event.get('message', '')}) |
|
|
yield build_accordion(progress_steps) |
|
|
elif event_type == "tool_call": |
|
|
tool = event.get("tool", "") |
|
|
tool_input = event.get("input", {}) |
|
|
|
|
|
if tool == "search_web": |
|
|
query = tool_input.get("query", "") if isinstance(tool_input, dict) else "" |
|
|
progress_steps.append({ |
|
|
"icon": "π", |
|
|
"icon_class": "tool", |
|
|
"title": f'<span class="mcp-tool-badge">MCP</span> search_web', |
|
|
"detail": f'Query: "{query[:60]}{"..." if len(query) > 60 else ""}"' |
|
|
}) |
|
|
elif tool == "search_news": |
|
|
progress_steps.append({ |
|
|
"icon": "π°", |
|
|
"icon_class": "tool", |
|
|
"title": f'<span class="mcp-tool-badge">MCP</span> search_news', |
|
|
"detail": "Searching for recent news..." |
|
|
}) |
|
|
elif tool == "discover_prospects_with_contacts": |
|
|
target = tool_input.get("target_prospects", num_prospects) if isinstance(tool_input, dict) else num_prospects |
|
|
progress_steps.append({ |
|
|
"icon": "π", |
|
|
"icon_class": "tool", |
|
|
"title": f'<span class="mcp-tool-badge">MCP</span> discover_prospects_with_contacts', |
|
|
"detail": f"Finding {target} prospects with verified contacts..." |
|
|
}) |
|
|
elif tool == "save_prospect": |
|
|
if isinstance(tool_input, dict): |
|
|
company = tool_input.get("company_name", "Unknown") |
|
|
current_prospect_name = company |
|
|
progress_steps.append({ |
|
|
"icon": "π―", |
|
|
"icon_class": "success", |
|
|
"title": f"Found prospect: <strong>{company}</strong>", |
|
|
"detail": tool_input.get("company_domain", "") |
|
|
}) |
|
|
|
|
|
pending_prospect = { |
|
|
"name": company, |
|
|
"domain": tool_input.get("company_domain", ""), |
|
|
"summary": tool_input.get("metadata", {}).get("summary", "") if isinstance(tool_input.get("metadata"), dict) else "", |
|
|
"industry": tool_input.get("metadata", {}).get("industry", "") if isinstance(tool_input.get("metadata"), dict) else "", |
|
|
"fit_reason": tool_input.get("metadata", {}).get("fit_reason", "") if isinstance(tool_input.get("metadata"), dict) else "", |
|
|
"fit_score": tool_input.get("fit_score", 0), |
|
|
"research_complete": True, |
|
|
"email_drafted": False, |
|
|
"discovered_at": datetime.now().strftime("%Y-%m-%d %H:%M") |
|
|
} |
|
|
elif tool == "save_contact": |
|
|
if isinstance(tool_input, dict): |
|
|
|
|
|
first_name = tool_input.get("first_name", "") |
|
|
last_name = tool_input.get("last_name", "") |
|
|
if first_name or last_name: |
|
|
name = f"{first_name} {last_name}".strip() |
|
|
else: |
|
|
name = tool_input.get("name", "Unknown") |
|
|
title = tool_input.get("title", "") |
|
|
|
|
|
company = tool_input.get("company_name") or current_prospect_name or "Unknown" |
|
|
if company.startswith("company_") or company.startswith("prospect_"): |
|
|
company = current_prospect_name or company |
|
|
progress_steps.append({ |
|
|
"icon": "π€", |
|
|
"icon_class": "success", |
|
|
"title": f"Found contact: <strong>{name}</strong>", |
|
|
"detail": f"{title} at {company}" |
|
|
}) |
|
|
|
|
|
pending_contact = { |
|
|
"name": name, |
|
|
"title": title or "Unknown", |
|
|
"email": tool_input.get("email", ""), |
|
|
"company": company, |
|
|
"linkedin": tool_input.get("linkedin_url", "") |
|
|
} |
|
|
elif tool == "send_email": |
|
|
progress_steps.append({ |
|
|
"icon": "βοΈ", |
|
|
"icon_class": "tool", |
|
|
"title": f'<span class="mcp-tool-badge">MCP</span> send_email', |
|
|
"detail": f"Drafting email for {current_prospect_name or 'prospect'}..." |
|
|
}) |
|
|
if isinstance(tool_input, dict): |
|
|
emails_drafted.append({ |
|
|
"to": tool_input.get("to", ""), |
|
|
"subject": tool_input.get("subject", ""), |
|
|
"body": tool_input.get("body", ""), |
|
|
"prospect_company": current_prospect_name or tool_input.get("prospect_id", "Unknown"), |
|
|
"created_at": datetime.now().strftime("%Y-%m-%d %H:%M") |
|
|
}) |
|
|
elif tool == "find_verified_contacts": |
|
|
company = tool_input.get("company_name", "company") if isinstance(tool_input, dict) else "company" |
|
|
progress_steps.append({ |
|
|
"icon": "π", |
|
|
"icon_class": "tool", |
|
|
"title": f'<span class="mcp-tool-badge">MCP</span> find_verified_contacts', |
|
|
"detail": f"Looking for decision makers at {company}..." |
|
|
}) |
|
|
|
|
|
yield build_accordion(progress_steps) |
|
|
progress(progress_pct) |
|
|
|
|
|
elif event_type == "tool_result": |
|
|
tool = event.get("tool", "") |
|
|
result = event.get("result", {}) |
|
|
|
|
|
if tool == "save_prospect": |
|
|
if pending_prospect: |
|
|
prospects_found.append(pending_prospect) |
|
|
pending_prospect = None |
|
|
|
|
|
elif tool == "save_contact": |
|
|
if pending_contact: |
|
|
contacts_found.append(pending_contact) |
|
|
pending_contact = None |
|
|
|
|
|
elif tool == "discover_prospects_with_contacts": |
|
|
|
|
|
if isinstance(result, dict): |
|
|
status = result.get("status", "") |
|
|
discovered_prospects = result.get("prospects", []) |
|
|
total_contacts = result.get("contacts_count", 0) |
|
|
companies_checked = result.get("companies_checked", 0) |
|
|
companies_skipped = result.get("companies_skipped", 0) |
|
|
message = result.get("message", "") |
|
|
|
|
|
progress_steps.append({ |
|
|
"icon": "π", |
|
|
"icon_class": "success", |
|
|
"title": "<strong>Discovery Complete!</strong>", |
|
|
"detail": f"Checked {companies_checked} companies, found {len(discovered_prospects)} with contacts" |
|
|
}) |
|
|
|
|
|
if discovered_prospects: |
|
|
for p in discovered_prospects: |
|
|
|
|
|
prospect_data = { |
|
|
"name": p.get("company_name", "Unknown"), |
|
|
"domain": p.get("domain", ""), |
|
|
"fit_score": p.get("fit_score", 75), |
|
|
"summary": p.get("summary", f"Found with {p.get('contact_count', 0)} verified contacts"), |
|
|
"industry": p.get("industry", "Technology & Services"), |
|
|
"fit_reason": p.get("fit_reason", "Matches target customer profile based on industry and company size"), |
|
|
"research_complete": True, |
|
|
"email_drafted": False, |
|
|
"discovered_at": datetime.now().strftime("%Y-%m-%d %H:%M") |
|
|
} |
|
|
prospects_found.append(prospect_data) |
|
|
|
|
|
progress_steps.append({ |
|
|
"icon": "β
", |
|
|
"icon_class": "success", |
|
|
"title": f"<strong>{p.get('company_name')}</strong>", |
|
|
"detail": f"{p.get('domain')} - {p.get('contact_count', 0)} contacts" |
|
|
}) |
|
|
|
|
|
|
|
|
for c in p.get("contacts", []): |
|
|
contact_data = { |
|
|
"name": c.get("name", "Unknown"), |
|
|
"email": c.get("email", ""), |
|
|
"title": c.get("title", ""), |
|
|
"company": p.get("company_name", ""), |
|
|
"verified": True, |
|
|
"source": c.get("source", "web_search") |
|
|
} |
|
|
contacts_found.append(contact_data) |
|
|
else: |
|
|
progress_steps.append({ |
|
|
"icon": "β οΈ", |
|
|
"icon_class": "warning", |
|
|
"title": "No prospects with verified contacts found", |
|
|
"detail": message |
|
|
}) |
|
|
|
|
|
yield build_accordion(progress_steps) |
|
|
|
|
|
elif tool == "find_verified_contacts": |
|
|
|
|
|
if isinstance(result, dict): |
|
|
status = result.get("status", "") |
|
|
found_contacts = result.get("contacts", []) |
|
|
message = result.get("message", "") |
|
|
|
|
|
if status == "success" and found_contacts: |
|
|
progress_steps.append({ |
|
|
"icon": "β
", |
|
|
"icon_class": "success", |
|
|
"title": f"Found {len(found_contacts)} verified contacts", |
|
|
"detail": ", ".join([c.get("name", "") for c in found_contacts[:3]]) |
|
|
}) |
|
|
for c in found_contacts: |
|
|
contact_data = { |
|
|
"name": c.get("name", "Unknown"), |
|
|
"email": c.get("email", ""), |
|
|
"title": c.get("title", ""), |
|
|
"company": c.get("company", current_prospect_name or ""), |
|
|
"verified": c.get("verified", True), |
|
|
"source": c.get("source", "web_search") |
|
|
} |
|
|
contacts_found.append(contact_data) |
|
|
elif status == "no_contacts_found": |
|
|
progress_steps.append({ |
|
|
"icon": "βοΈ", |
|
|
"icon_class": "warning", |
|
|
"title": "No contacts found", |
|
|
"detail": message |
|
|
}) |
|
|
|
|
|
yield build_accordion(progress_steps) |
|
|
|
|
|
elif tool == "send_email": |
|
|
progress_steps.append({ |
|
|
"icon": "β
", |
|
|
"icon_class": "success", |
|
|
"title": "Email drafted", |
|
|
"detail": f"For {current_prospect_name or 'prospect'}" |
|
|
}) |
|
|
|
|
|
if prospects_found: |
|
|
prospects_found[-1]["email_drafted"] = True |
|
|
yield build_accordion(progress_steps) |
|
|
|
|
|
elif tool in ["search_web", "search_news"]: |
|
|
count = result.get("count", 0) if isinstance(result, dict) else 0 |
|
|
|
|
|
if progress_steps and "search" in progress_steps[-1].get("title", "").lower(): |
|
|
progress_steps[-1]["detail"] += f" β Found {count} results" |
|
|
|
|
|
if isinstance(result, dict) and result.get("results"): |
|
|
for r in result.get("results", []): |
|
|
if isinstance(r, dict): |
|
|
title = r.get("title", "") |
|
|
snippet = r.get("body", r.get("text", r.get("snippet", r.get("description", "")))) |
|
|
url = r.get("url", r.get("source", r.get("link", ""))) |
|
|
if title: |
|
|
search_results_for_prospects.append({ |
|
|
"title": title, |
|
|
"snippet": snippet, |
|
|
"url": url |
|
|
}) |
|
|
yield build_accordion(progress_steps) |
|
|
|
|
|
elif event_type == "thought": |
|
|
|
|
|
thought = event.get("thought", "") |
|
|
message = event.get("message", "") |
|
|
|
|
|
if thought and "CX AI Agent" not in thought and "Powered by AI" not in thought and not thought.startswith("[Processing:"): |
|
|
last_final_answer = thought |
|
|
|
|
|
elif event_type == "agent_complete": |
|
|
|
|
|
if contacts_found and not emails_drafted: |
|
|
progress_steps.append({ |
|
|
"icon": "βοΈ", |
|
|
"icon_class": "tool", |
|
|
"title": "Auto-drafting outreach emails...", |
|
|
"detail": f"Creating personalized emails for {len(contacts_found)} contacts" |
|
|
}) |
|
|
yield build_accordion(progress_steps) |
|
|
|
|
|
for c in contacts_found: |
|
|
if c.get("email"): |
|
|
contact_name = c.get("name", "").split()[0] if c.get("name") else "there" |
|
|
full_name = c.get("name", "") |
|
|
company = c.get("company", "your company") |
|
|
title = c.get("title", "") |
|
|
|
|
|
email_body = f"""Hi {contact_name}, |
|
|
|
|
|
I hope this message finds you well. I recently came across {company} and was genuinely impressed by the innovative work your team is doing in the industry. |
|
|
|
|
|
As {title} at {company}, you're likely focused on driving growth and staying ahead of industry trends. That's exactly why I wanted to reach out. |
|
|
|
|
|
At {client_name}, we specialize in helping companies like {company} achieve their strategic objectives through tailored solutions. We've helped similar organizations: |
|
|
|
|
|
β’ Streamline their operations and reduce costs |
|
|
β’ Accelerate growth through innovative strategies |
|
|
β’ Stay competitive in an evolving market |
|
|
|
|
|
I'd love to share some specific insights that have worked well for companies in your space. Would you be open to a brief 15-minute call this week to explore if there might be a fit? |
|
|
|
|
|
I'm flexible on timing and happy to work around your schedule. |
|
|
|
|
|
Looking forward to connecting, |
|
|
|
|
|
Best regards, |
|
|
{client_name} Team |
|
|
|
|
|
P.S. If you're not the right person to speak with about this, I'd greatly appreciate it if you could point me in the right direction.""" |
|
|
|
|
|
emails_drafted.append({ |
|
|
"to": c.get("email"), |
|
|
"subject": f"{contact_name}, quick question about {company}'s 2025 growth plans", |
|
|
"body": email_body, |
|
|
"prospect_company": company, |
|
|
"contact_name": full_name, |
|
|
"created_at": datetime.now().strftime("%Y-%m-%d %H:%M") |
|
|
}) |
|
|
|
|
|
progress_steps.append({ |
|
|
"icon": "β
", |
|
|
"icon_class": "success", |
|
|
"title": f"Drafted {len(emails_drafted)} outreach emails", |
|
|
"detail": "Ready for review in the Emails tab" |
|
|
}) |
|
|
yield build_accordion(progress_steps) |
|
|
|
|
|
|
|
|
merge_to_knowledge_base(prospects_found, contacts_found, emails_drafted) |
|
|
|
|
|
|
|
|
summary_html = f'''<div class="progress-summary"> |
|
|
<h3>β
Discovery Complete!</h3> |
|
|
<table> |
|
|
<tr><td>Prospects Found</td><td><strong>{len(prospects_found)}</strong></td></tr> |
|
|
<tr><td>Decision Makers</td><td><strong>{len(contacts_found)}</strong></td></tr> |
|
|
<tr><td>Emails Drafted</td><td><strong>{len(emails_drafted)}</strong></td></tr> |
|
|
</table> |
|
|
</div>''' |
|
|
|
|
|
|
|
|
results_html = "" |
|
|
if prospects_found or contacts_found or emails_drafted: |
|
|
results_html += """<div style="margin-top: 20px;"> |
|
|
<h3 style="color: var(--text-primary); margin-bottom: 16px;">π― Discovered Prospects</h3>""" |
|
|
|
|
|
for p in prospects_found: |
|
|
p_name = p.get('name', 'Unknown') |
|
|
p_name_lower = p_name.lower() |
|
|
|
|
|
|
|
|
p_domain = p.get('domain', '').lower().replace('www.', '') |
|
|
p_contacts = [] |
|
|
for c in contacts_found: |
|
|
c_company = c.get("company", "").lower() |
|
|
c_email = c.get("email", "").lower() |
|
|
|
|
|
if (c_company == p_name_lower or |
|
|
p_name_lower == c_company or |
|
|
(p_domain and p_domain in c_email)): |
|
|
p_contacts.append(c) |
|
|
|
|
|
|
|
|
p_emails = [] |
|
|
for e in emails_drafted: |
|
|
e_company = e.get("prospect_company", "").lower() |
|
|
e_to = e.get("to", "").lower() |
|
|
if (e_company == p_name_lower or |
|
|
p_name_lower == e_company or |
|
|
(p_domain and p_domain in e_to)): |
|
|
p_emails.append(e) |
|
|
|
|
|
|
|
|
contacts_section = "" |
|
|
if p_contacts: |
|
|
contacts_section = "<div style='margin-top: 12px;'><strong style='color: var(--text-primary);'>π₯ Decision Makers:</strong><ul style='margin: 8px 0 0 0; padding-left: 20px;'>" |
|
|
for c in p_contacts: |
|
|
contacts_section += f"<li><strong>{c.get('name', 'Unknown')}</strong> - {c.get('title', 'Unknown')}" |
|
|
if c.get('email'): |
|
|
contacts_section += f" <span style='color: var(--primary-blue);'>({c.get('email')})</span>" |
|
|
contacts_section += "</li>" |
|
|
contacts_section += "</ul></div>" |
|
|
|
|
|
|
|
|
emails_section = "" |
|
|
if p_emails: |
|
|
emails_section = "<div style='margin-top: 12px;'><details style='background: var(--bg-secondary); border-radius: 8px; padding: 0;'>" |
|
|
emails_section += f"<summary style='padding: 10px 14px; cursor: pointer; font-weight: 600; color: var(--primary-blue);'>βοΈ View Outreach Email ({len(p_emails)})</summary>" |
|
|
emails_section += "<div style='padding: 12px 14px; border-top: 1px solid var(--border-color);'>" |
|
|
for e in p_emails: |
|
|
email_body = e.get('body', '').replace('\n', '<br>') |
|
|
emails_section += f""" |
|
|
<div style='margin-bottom: 12px;'> |
|
|
<div style='font-size: 12px; color: #666;'><strong>To:</strong> {e.get('to', 'Unknown')}</div> |
|
|
<div style='font-size: 13px; font-weight: 600; color: #333; margin: 6px 0;'><strong>Subject:</strong> {e.get('subject', 'No subject')}</div> |
|
|
<div style='font-size: 13px; color: #333; line-height: 1.6; background: #f8f9fa; padding: 14px; border-radius: 6px; border: 1px solid #dee2e6;'>{email_body}</div> |
|
|
</div>""" |
|
|
emails_section += "</div></details></div>" |
|
|
|
|
|
results_html += f""" |
|
|
<details class="prospect-card" style="margin-bottom: 12px;" open> |
|
|
<summary class="prospect-card-header" style="padding: 14px 18px;"> |
|
|
<span class="prospect-card-title">π’ {p_name}</span> |
|
|
<span class="prospect-card-badge badge-researched">{'βοΈ EMAIL READY' if p_emails else 'β
DISCOVERED'}</span> |
|
|
</summary> |
|
|
<div class="prospect-card-details" style="padding: 16px 18px;"> |
|
|
<div style="display: grid; grid-template-columns: 1fr 1fr; gap: 12px; margin-bottom: 12px;"> |
|
|
<div><strong style="color: var(--text-secondary); font-size: 12px;">π INDUSTRY</strong><div style="color: var(--text-primary);">{p.get('industry', 'Technology & Services')}</div></div> |
|
|
<div><strong style="color: var(--text-secondary); font-size: 12px;">π DOMAIN</strong><div style="color: var(--text-primary);">{p.get('domain', 'N/A')}</div></div> |
|
|
</div> |
|
|
<div style="margin-bottom: 12px;"><strong style="color: var(--text-secondary); font-size: 12px;">π SUMMARY</strong><div style="color: var(--text-primary); font-size: 13px; margin-top: 4px;">{p.get('summary', 'No summary available')}</div></div> |
|
|
<div style="margin-bottom: 12px;"><strong style="color: var(--text-secondary); font-size: 12px;">π― FIT REASON</strong><div style="color: var(--text-primary); font-size: 13px; margin-top: 4px;">{p.get('fit_reason', 'Matches target customer profile')}</div></div> |
|
|
{contacts_section} |
|
|
{emails_section} |
|
|
</div> |
|
|
</details>""" |
|
|
|
|
|
results_html += "</div>" |
|
|
elif not prospects_found: |
|
|
results_html = """<div style="margin-top: 20px; background: #fff3cd; border: 1px solid #ffc107; border-radius: 8px; padding: 14px;"> |
|
|
<strong>βΉοΈ Note:</strong> No prospects were saved by the AI. Try running discovery again or adjusting your search criteria. |
|
|
</div>""" |
|
|
|
|
|
|
|
|
yield build_accordion(progress_steps, is_loading=False, summary_html=summary_html + results_html) |
|
|
progress(1.0) |
|
|
return |
|
|
|
|
|
elif event_type == "agent_max_iterations": |
|
|
|
|
|
if contacts_found and not emails_drafted: |
|
|
for c in contacts_found: |
|
|
if c.get("email"): |
|
|
contact_name = c.get("name", "").split()[0] if c.get("name") else "there" |
|
|
full_name = c.get("name", "") |
|
|
company = c.get("company", "your company") |
|
|
title = c.get("title", "") |
|
|
email_body = f"""Hi {contact_name}, |
|
|
|
|
|
I hope this message finds you well. I recently came across {company} and was genuinely impressed by the innovative work your team is doing. |
|
|
|
|
|
As {title} at {company}, you're likely focused on driving growth and staying ahead of industry trends. That's exactly why I wanted to reach out. |
|
|
|
|
|
At {client_name}, we specialize in helping companies like {company} achieve their strategic objectives. We've helped similar organizations: |
|
|
|
|
|
β’ Streamline their operations and reduce costs |
|
|
β’ Accelerate growth through innovative strategies |
|
|
β’ Stay competitive in an evolving market |
|
|
|
|
|
Would you be open to a brief 15-minute call this week to explore if there might be a fit? |
|
|
|
|
|
Best regards, |
|
|
{client_name} Team""" |
|
|
emails_drafted.append({ |
|
|
"to": c.get("email"), |
|
|
"subject": f"{contact_name}, quick question about {company}'s 2025 growth plans", |
|
|
"body": email_body, |
|
|
"prospect_company": company, |
|
|
"contact_name": full_name, |
|
|
"created_at": datetime.now().strftime("%Y-%m-%d %H:%M") |
|
|
}) |
|
|
|
|
|
|
|
|
merge_to_knowledge_base(prospects_found, contacts_found, emails_drafted) |
|
|
|
|
|
progress_steps.append({ |
|
|
"icon": "β±οΈ", |
|
|
"icon_class": "warning", |
|
|
"title": "Max iterations reached", |
|
|
"detail": "Discovery stopped but results saved" |
|
|
}) |
|
|
|
|
|
summary_html = f'''<div class="progress-summary" style="background: linear-gradient(135deg, #f39c12 0%, #e67e22 100%);"> |
|
|
<h3>β±οΈ Discovery Summary (Partial)</h3> |
|
|
<table> |
|
|
<tr><td>Prospects Found</td><td><strong>{len(prospects_found)}</strong></td></tr> |
|
|
<tr><td>Decision Makers</td><td><strong>{len(contacts_found)}</strong></td></tr> |
|
|
<tr><td>Emails Drafted</td><td><strong>{len(emails_drafted)}</strong></td></tr> |
|
|
</table> |
|
|
</div>''' |
|
|
yield build_accordion(progress_steps, is_loading=False, summary_html=summary_html) |
|
|
return |
|
|
|
|
|
elif event_type == "agent_error": |
|
|
|
|
|
merge_to_knowledge_base(prospects_found, contacts_found, emails_drafted) |
|
|
|
|
|
error_msg = event.get("error", "Unknown error") |
|
|
progress_steps.append({ |
|
|
"icon": "β", |
|
|
"icon_class": "error", |
|
|
"title": "Error occurred", |
|
|
"detail": str(error_msg)[:100] |
|
|
}) |
|
|
|
|
|
summary_html = f'''<div class="progress-summary" style="background: linear-gradient(135deg, #e74c3c 0%, #c0392b 100%);"> |
|
|
<h3>β οΈ Discovery Interrupted</h3> |
|
|
<table> |
|
|
<tr><td>Prospects Found</td><td><strong>{len(prospects_found)}</strong></td></tr> |
|
|
<tr><td>Decision Makers</td><td><strong>{len(contacts_found)}</strong></td></tr> |
|
|
<tr><td>Emails Drafted</td><td><strong>{len(emails_drafted)}</strong></td></tr> |
|
|
</table> |
|
|
</div>''' |
|
|
yield build_accordion(progress_steps, is_loading=False, summary_html=summary_html) |
|
|
return |
|
|
|
|
|
except Exception as e: |
|
|
logger.error(f"Discovery error: {e}") |
|
|
|
|
|
merge_to_knowledge_base(prospects_found, contacts_found, emails_drafted) |
|
|
|
|
|
progress_steps.append({ |
|
|
"icon": "β", |
|
|
"icon_class": "error", |
|
|
"title": "Discovery interrupted", |
|
|
"detail": str(e)[:100] |
|
|
}) |
|
|
|
|
|
summary_html = f'''<div class="progress-summary" style="background: linear-gradient(135deg, #e74c3c 0%, #c0392b 100%);"> |
|
|
<h3>β οΈ Discovery Error</h3> |
|
|
<p>Saved {len(prospects_found)} prospects found so far.</p> |
|
|
</div>''' |
|
|
yield build_accordion(progress_steps, is_loading=False, summary_html=summary_html) |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
async def chat_with_ai_async(message: str, history: list, hf_token: str): |
|
|
"""AI Chat powered by LLM with full MCP tool support""" |
|
|
if not knowledge_base["client"]["name"]: |
|
|
yield history + [[message, "β οΈ Please complete Setup first. Enter your company name in the Setup tab."]], "" |
|
|
return |
|
|
|
|
|
if not message.strip(): |
|
|
yield history, "" |
|
|
return |
|
|
|
|
|
token = get_hf_token(hf_token) |
|
|
if not token: |
|
|
yield history + [[message, "β οΈ Please enter your HuggingFace token in the Setup tab."]], "" |
|
|
return |
|
|
|
|
|
client_name = knowledge_base["client"]["name"] |
|
|
client_info = knowledge_base["client"].get("raw_research", "") |
|
|
|
|
|
|
|
|
try: |
|
|
agent = AutonomousMCPAgentHF( |
|
|
mcp_registry=mcp_registry, |
|
|
hf_token=token, |
|
|
provider=HF_PROVIDER, |
|
|
model=HF_MODEL |
|
|
) |
|
|
|
|
|
|
|
|
prospects_detail = "" |
|
|
if knowledge_base["prospects"]: |
|
|
for i, p in enumerate(knowledge_base["prospects"][:10], 1): |
|
|
p_name = p.get('name', 'Unknown') |
|
|
p_name_lower = p_name.lower() |
|
|
|
|
|
p_contacts = [c for c in knowledge_base["contacts"] |
|
|
if p_name_lower in c.get("company", "").lower() |
|
|
or c.get("company", "").lower() in p_name_lower] |
|
|
contacts_str = ", ".join([f"{c.get('name')} ({c.get('email')})" for c in p_contacts]) if p_contacts else "No contacts" |
|
|
prospects_detail += f"{i}. {p_name} - {p.get('industry', 'Unknown industry')}, Fit: {p.get('fit_score', 'N/A')}\n" |
|
|
prospects_detail += f" Summary: {p.get('summary', 'No summary')[:100]}\n" |
|
|
prospects_detail += f" Contacts: {contacts_str}\n" |
|
|
else: |
|
|
prospects_detail = "No prospects discovered yet." |
|
|
|
|
|
emails_detail = "" |
|
|
if knowledge_base["emails"]: |
|
|
for e in knowledge_base["emails"][:5]: |
|
|
emails_detail += f"- To: {e.get('to')} | Subject: {e.get('subject', 'No subject')[:50]}\n" |
|
|
else: |
|
|
emails_detail = "No emails drafted yet." |
|
|
|
|
|
task = f"""You are an AI sales assistant for {client_name}. You are a helpful, knowledgeable assistant that can answer any question about the sales pipeline, prospects, contacts, and help with various sales tasks. |
|
|
|
|
|
ABOUT {client_name}: |
|
|
{client_info[:500] if client_info else "No company research available yet."} |
|
|
|
|
|
CURRENT SALES PIPELINE: |
|
|
====================== |
|
|
PROSPECTS ({len(knowledge_base['prospects'])}): |
|
|
{prospects_detail} |
|
|
|
|
|
CONTACTS ({len(knowledge_base['contacts'])}): |
|
|
{len(knowledge_base['contacts'])} decision makers found across prospects. |
|
|
|
|
|
DRAFTED EMAILS ({len(knowledge_base['emails'])}): |
|
|
{emails_detail} |
|
|
|
|
|
USER MESSAGE: {message} |
|
|
|
|
|
INSTRUCTIONS: |
|
|
- Answer the user's question helpfully and completely |
|
|
- If they ask about prospects, contacts, or emails, use the data above |
|
|
- If they ask you to search for something, use search_web tool |
|
|
- If they ask you to draft an email, create a professional, personalized email |
|
|
- If they ask for talking points, strategies, or recommendations, provide thoughtful, specific advice |
|
|
- If they ask to find similar companies or new prospects, use search_web to research |
|
|
- Be conversational and helpful - you're a knowledgeable sales assistant |
|
|
- Don't say "I don't have that capability" - try to help with whatever they ask |
|
|
- For follow-up questions, use context from the conversation |
|
|
|
|
|
Respond naturally and helpfully to the user's message.""" |
|
|
|
|
|
response_text = "" |
|
|
current_history = history + [[message, "π€ Thinking..."]] |
|
|
yield current_history, "" |
|
|
|
|
|
async for event in agent.run(task, max_iterations=12): |
|
|
event_type = event.get("type") |
|
|
|
|
|
if event_type == "tool_call": |
|
|
tool = event.get("tool", "") |
|
|
tool_input = event.get("input", {}) |
|
|
if tool == "search_web": |
|
|
query = tool_input.get("query", "") if isinstance(tool_input, dict) else "" |
|
|
response_text += f"π Searching: {query[:50]}...\n" |
|
|
elif tool == "send_email": |
|
|
response_text += f"βοΈ Drafting email...\n" |
|
|
else: |
|
|
response_text += f"π§ Using {tool}...\n" |
|
|
current_history = history + [[message, response_text]] |
|
|
yield current_history, "" |
|
|
|
|
|
elif event_type == "tool_result": |
|
|
tool = event.get("tool", "") |
|
|
result = event.get("result", {}) |
|
|
|
|
|
|
|
|
if tool == "save_prospect" and isinstance(result, dict): |
|
|
prospect_data = { |
|
|
"name": result.get("company_name", result.get("prospect_id", "Unknown")), |
|
|
"domain": result.get("company_domain", result.get("domain", "")), |
|
|
"fit_score": result.get("fit_score", 75), |
|
|
"research_complete": True, |
|
|
"discovered_at": datetime.now().strftime("%Y-%m-%d %H:%M") |
|
|
} |
|
|
merge_to_knowledge_base([prospect_data], [], []) |
|
|
response_text += f"β
Saved prospect: {prospect_data['name']}\n" |
|
|
|
|
|
elif tool == "save_contact" and isinstance(result, dict): |
|
|
merge_to_knowledge_base([], [result], []) |
|
|
response_text += f"β
Saved contact\n" |
|
|
|
|
|
elif tool == "send_email" and isinstance(result, dict): |
|
|
merge_to_knowledge_base([], [], [result]) |
|
|
response_text += f"β
Email drafted\n" |
|
|
|
|
|
elif tool == "search_web": |
|
|
count = result.get("count", 0) if isinstance(result, dict) else 0 |
|
|
response_text += f"β
Found {count} results\n" |
|
|
|
|
|
current_history = history + [[message, response_text]] |
|
|
yield current_history, "" |
|
|
|
|
|
elif event_type == "thought": |
|
|
thought = event.get("thought", "") |
|
|
|
|
|
if thought and len(thought) > 50 and not thought.startswith("[Processing"): |
|
|
|
|
|
pass |
|
|
|
|
|
elif event_type == "agent_complete": |
|
|
final = event.get("final_answer", "") |
|
|
if final and "CX AI Agent" not in final and "Powered by AI" not in final: |
|
|
|
|
|
if response_text: |
|
|
response_text += "\n---\n\n" |
|
|
response_text += final |
|
|
elif not response_text: |
|
|
response_text = "I've processed your request. Is there anything else you'd like to know?" |
|
|
current_history = history + [[message, response_text]] |
|
|
yield current_history, "" |
|
|
return |
|
|
|
|
|
elif event_type == "agent_error": |
|
|
error = event.get("error", "Unknown error") |
|
|
if "rate limit" in str(error).lower(): |
|
|
response_text += "\nβ οΈ Rate limit reached. Please wait a moment and try again." |
|
|
else: |
|
|
response_text += f"\nβ οΈ Error: {error}" |
|
|
current_history = history + [[message, response_text]] |
|
|
yield current_history, "" |
|
|
return |
|
|
|
|
|
elif event_type == "agent_max_iterations": |
|
|
if not response_text: |
|
|
response_text = "I'm still processing your request. The task may be complex - please try a simpler question or try again." |
|
|
current_history = history + [[message, response_text]] |
|
|
yield current_history, "" |
|
|
return |
|
|
|
|
|
|
|
|
if not response_text: |
|
|
response_text = "I processed your request. Let me know if you need anything else!" |
|
|
yield history + [[message, response_text]], "" |
|
|
|
|
|
except Exception as e: |
|
|
logger.error(f"Chat agent error: {e}") |
|
|
error_msg = str(e) |
|
|
if "rate limit" in error_msg.lower() or "429" in error_msg: |
|
|
yield history + [[message, "β οΈ Rate limit reached. Please wait a moment and try again."]], "" |
|
|
else: |
|
|
yield history + [[message, f"β οΈ Error: {error_msg}"]], "" |
|
|
|
|
|
|
|
|
def chat_with_ai(message: str, history: list) -> tuple: |
|
|
"""Chat function - handles queries using local data and templates""" |
|
|
if not knowledge_base["client"]["name"]: |
|
|
return history + [[message, "β οΈ Please complete Setup first. Enter your HuggingFace token and company name."]], "" |
|
|
|
|
|
if not session_hf_token.get("token"): |
|
|
return history + [[message, "β οΈ Please enter your HuggingFace token in the **Setup** tab first."]], "" |
|
|
|
|
|
if not message.strip(): |
|
|
return history, "" |
|
|
|
|
|
client_name = knowledge_base["client"]["name"] |
|
|
msg_lower = message.lower() |
|
|
|
|
|
def find_prospect_by_name(query: str): |
|
|
"""Find prospect by exact or partial name match""" |
|
|
query_lower = query.lower() |
|
|
|
|
|
for p in knowledge_base["prospects"]: |
|
|
if p.get("name", "").lower() == query_lower: |
|
|
return p |
|
|
|
|
|
for p in knowledge_base["prospects"]: |
|
|
if query_lower in p.get("name", "").lower(): |
|
|
return p |
|
|
|
|
|
for p in knowledge_base["prospects"]: |
|
|
p_name = p.get("name", "").lower() |
|
|
if p_name in query_lower: |
|
|
return p |
|
|
|
|
|
query_words = set(query_lower.split()) |
|
|
for p in knowledge_base["prospects"]: |
|
|
p_words = set(p.get("name", "").lower().split()) |
|
|
if query_words & p_words: |
|
|
return p |
|
|
return None |
|
|
|
|
|
|
|
|
mentioned_prospect = find_prospect_by_name(message) |
|
|
|
|
|
|
|
|
if any(kw in msg_lower for kw in ["find decision", "find contact", "who works at", "contacts at"]): |
|
|
if mentioned_prospect: |
|
|
p_name = mentioned_prospect["name"] |
|
|
p_name_lower = p_name.lower() |
|
|
contacts = [c for c in knowledge_base["contacts"] |
|
|
if p_name_lower in c.get("company", "").lower() |
|
|
or c.get("company", "").lower() in p_name_lower] |
|
|
|
|
|
if contacts: |
|
|
response = f"## π₯ Decision Makers at {p_name}\n\n" |
|
|
for c in contacts: |
|
|
response += f"**{c.get('name', 'Unknown')}** - {c.get('title', 'Unknown')}\n" |
|
|
response += f" - Email: {c.get('email', 'Not available')}\n" |
|
|
response += f" - Company: {c.get('company', p_name)}\n\n" |
|
|
else: |
|
|
response = f"No contacts found yet for **{p_name}**.\n\n" |
|
|
response += "To find contacts, go to **Prospects Tab** and run **Find Prospects** again." |
|
|
return history + [[message, response]], "" |
|
|
|
|
|
|
|
|
if any(kw in msg_lower for kw in ["show email", "existing email", "what email", "see email", "view email"]): |
|
|
if mentioned_prospect: |
|
|
p_name = mentioned_prospect["name"] |
|
|
p_name_lower = p_name.lower() |
|
|
existing_emails = [e for e in knowledge_base["emails"] |
|
|
if p_name_lower in e.get("prospect_company", "").lower()] |
|
|
if existing_emails: |
|
|
email = existing_emails[0] |
|
|
response = f"## βοΈ Existing Email Draft for {p_name}\n\n" |
|
|
response += f"**To:** {email.get('to', 'N/A')}\n" |
|
|
response += f"**Subject:** {email.get('subject', 'N/A')}\n\n" |
|
|
response += f"---\n\n{email.get('body', 'No content')}\n\n" |
|
|
response += "---\n\n*This email was drafted during prospect discovery.*" |
|
|
else: |
|
|
response = f"No existing email drafts found for **{p_name}**." |
|
|
return history + [[message, response]], "" |
|
|
|
|
|
|
|
|
if any(kw in msg_lower for kw in ["draft", "write", "compose", "create email", "email to", "send email", "mail to"]): |
|
|
if mentioned_prospect: |
|
|
p_name = mentioned_prospect["name"] |
|
|
p_name_lower = p_name.lower() |
|
|
|
|
|
|
|
|
contacts = [c for c in knowledge_base["contacts"] |
|
|
if p_name_lower in c.get("company", "").lower() |
|
|
or c.get("company", "").lower() in p_name_lower] |
|
|
contact = contacts[0] if contacts else None |
|
|
to_email = contact.get("email", f"contact@{p_name.lower().replace(' ', '')}.com") if contact else f"contact@{p_name.lower().replace(' ', '')}.com" |
|
|
contact_name = contact.get("name", "").split()[0] if contact and contact.get("name") else "there" |
|
|
contact_title = contact.get("title", "") if contact else "" |
|
|
|
|
|
|
|
|
import re |
|
|
|
|
|
|
|
|
is_meeting_request = any(kw in msg_lower for kw in ["meeting", "call", "demo", "schedule", "appointment"]) |
|
|
|
|
|
|
|
|
date_match = re.search(r'(\d{1,2}(?:st|nd|rd|th)?\s+(?:jan|feb|mar|apr|may|jun|jul|aug|sep|oct|nov|dec)[a-z]*\s+\d{4}|\w+day(?:\s+next\s+week)?|\d{1,2}[/-]\d{1,2}[/-]\d{2,4})', msg_lower) |
|
|
time_match = re.search(r'(\d{1,2}:\d{2}|\d{1,2}\s*(?:am|pm))', msg_lower) |
|
|
duration_match = re.search(r'(\d+)\s*(?:min|minute|hour)', msg_lower) |
|
|
|
|
|
date_str = date_match.group(1).title() if date_match else "" |
|
|
time_str = time_match.group(1) if time_match else "" |
|
|
duration_str = duration_match.group(0) if duration_match else "" |
|
|
|
|
|
|
|
|
|
|
|
custom_content = message |
|
|
for word in ["draft", "write", "compose", "email", "mail", "to", p_name.lower(), "asking", "that", "can", "we", "a", "an", "the", "for", "about"]: |
|
|
custom_content = re.sub(rf'\b{word}\b', '', custom_content, flags=re.IGNORECASE) |
|
|
custom_content = ' '.join(custom_content.split()).strip() |
|
|
|
|
|
|
|
|
response = f"## βοΈ Custom Email Draft for {p_name}\n\n" |
|
|
response += f"**To:** {to_email}\n" |
|
|
|
|
|
if is_meeting_request: |
|
|
|
|
|
subject = f"Meeting Request: {client_name} x {p_name}" |
|
|
if date_str: |
|
|
subject = f"Meeting Request for {date_str} - {client_name} x {p_name}" |
|
|
response += f"**Subject:** {subject}\n\n" |
|
|
response += f"---\n\n" |
|
|
response += f"Dear {contact_name},\n\n" |
|
|
response += f"I hope this email finds you well.\n\n" |
|
|
response += f"I'm reaching out from {client_name} regarding a potential collaboration with {p_name}. " |
|
|
response += f"Based on our research, we believe there's a strong synergy between our companies, " |
|
|
response += f"particularly in the {mentioned_prospect.get('industry', 'your industry')} space.\n\n" |
|
|
|
|
|
if date_str or time_str or duration_str: |
|
|
response += f"I would like to propose a meeting" |
|
|
if date_str: |
|
|
response += f" on **{date_str}**" |
|
|
if time_str: |
|
|
response += f" at **{time_str}**" |
|
|
if duration_str: |
|
|
response += f" for **{duration_str}**" |
|
|
response += f" to discuss how {client_name} can help {p_name} achieve its goals.\n\n" |
|
|
else: |
|
|
response += f"Would you be available for a brief call this week to discuss how {client_name} can support {p_name}'s growth?\n\n" |
|
|
|
|
|
response += f"During our conversation, I'd love to explore:\n" |
|
|
response += f"- How {client_name}'s solutions align with {p_name}'s current initiatives\n" |
|
|
response += f"- Specific ways we can add value to your {mentioned_prospect.get('industry', 'business')}\n" |
|
|
response += f"- Next steps for a potential partnership\n\n" |
|
|
response += f"Please let me know if this time works for you, or suggest an alternative that fits your schedule.\n\n" |
|
|
else: |
|
|
|
|
|
subject = f"{client_name} + {p_name}: Let's Connect" |
|
|
response += f"**Subject:** {subject}\n\n" |
|
|
response += f"---\n\n" |
|
|
response += f"Dear {contact_name},\n\n" |
|
|
response += f"I'm reaching out from {client_name} regarding {p_name}.\n\n" |
|
|
if custom_content: |
|
|
response += f"{custom_content}\n\n" |
|
|
response += f"Based on our research into {p_name}'s work in {mentioned_prospect.get('industry', 'your industry')}, " |
|
|
response += f"we believe {client_name} can provide significant value.\n\n" |
|
|
response += f"**About {p_name}:** {mentioned_prospect.get('summary', '')}\n\n" |
|
|
response += f"**Why we're reaching out:** {mentioned_prospect.get('fit_reason', 'We see great potential for collaboration.')}\n\n" |
|
|
response += f"Would you be open to a conversation about how we can work together?\n\n" |
|
|
|
|
|
response += f"Best regards,\n" |
|
|
response += f"[Your Name]\n" |
|
|
response += f"{client_name}\n\n" |
|
|
response += f"---\n\n" |
|
|
response += f"*π This is a custom draft based on your request. Edit as needed before sending.*" |
|
|
|
|
|
return history + [[message, response]], "" |
|
|
|
|
|
|
|
|
if any(kw in msg_lower for kw in ["talking point", "suggest", "recommend", "strategy"]): |
|
|
if mentioned_prospect: |
|
|
p_name = mentioned_prospect["name"] |
|
|
response = f"## π‘ Talking Points for {p_name}\n\n" |
|
|
response += f"**About {p_name}:**\n" |
|
|
response += f"- Industry: {mentioned_prospect.get('industry', 'Unknown')}\n" |
|
|
response += f"- {mentioned_prospect.get('summary', 'No summary available')}\n\n" |
|
|
response += f"**Why they're a fit for {client_name}:**\n" |
|
|
response += f"- {mentioned_prospect.get('fit_reason', 'Matches target customer profile')}\n\n" |
|
|
response += f"**Suggested talking points:**\n" |
|
|
response += f"1. Reference their focus on {mentioned_prospect.get('industry', 'their industry')}\n" |
|
|
response += f"2. Highlight how {client_name} can help with scalability\n" |
|
|
response += f"3. Mention success stories from similar companies\n" |
|
|
response += f"4. Propose a specific next step (demo, call, pilot)\n" |
|
|
return history + [[message, response]], "" |
|
|
|
|
|
|
|
|
if any(kw in msg_lower for kw in ["research", "analyze", "details about", "info on", "information about"]): |
|
|
if mentioned_prospect: |
|
|
p_name = mentioned_prospect["name"] |
|
|
p_name_lower = p_name.lower() |
|
|
|
|
|
|
|
|
contacts = [c for c in knowledge_base["contacts"] |
|
|
if p_name_lower in c.get("company", "").lower() |
|
|
or c.get("company", "").lower() in p_name_lower] |
|
|
emails = [e for e in knowledge_base["emails"] |
|
|
if p_name_lower in e.get("prospect_company", "").lower()] |
|
|
|
|
|
response = f"## π Research: {p_name}\n\n" |
|
|
response += f"### Company Overview\n" |
|
|
response += f"- **Industry:** {mentioned_prospect.get('industry', 'Unknown')}\n" |
|
|
response += f"- **Fit Score:** {mentioned_prospect.get('fit_score', 'N/A')}/100\n" |
|
|
response += f"- **Summary:** {mentioned_prospect.get('summary', 'No summary available')}\n\n" |
|
|
|
|
|
response += f"### Why They're a Good Fit for {client_name}\n" |
|
|
response += f"{mentioned_prospect.get('fit_reason', 'Matches target customer profile')}\n\n" |
|
|
|
|
|
response += f"### Decision Makers ({len(contacts)})\n" |
|
|
if contacts: |
|
|
for c in contacts: |
|
|
response += f"- **{c.get('name', 'Unknown')}** - {c.get('title', 'Unknown')}\n" |
|
|
response += f" - Email: {c.get('email', 'N/A')}\n" |
|
|
else: |
|
|
response += "No contacts found yet.\n" |
|
|
|
|
|
response += f"\n### Outreach Status\n" |
|
|
if emails: |
|
|
response += f"β
{len(emails)} email(s) drafted\n" |
|
|
for e in emails: |
|
|
response += f"- To: {e.get('to', 'N/A')} - \"{e.get('subject', 'No subject')[:40]}...\"\n" |
|
|
else: |
|
|
response += "β³ No emails drafted yet\n" |
|
|
|
|
|
return history + [[message, response]], "" |
|
|
|
|
|
|
|
|
if any(kw in msg_lower for kw in ["competitor", "similar to", "like "]): |
|
|
if mentioned_prospect: |
|
|
p_name = mentioned_prospect["name"] |
|
|
industry = mentioned_prospect.get('industry', 'Unknown') |
|
|
response = f"## π’ Finding Similar Companies to {p_name}\n\n" |
|
|
response += f"**{p_name}** is in the **{industry}** industry.\n\n" |
|
|
response += f"To find more companies similar to {p_name}:\n\n" |
|
|
response += f"1. Go to **Prospects Tab**\n" |
|
|
response += f"2. The AI will search for companies in {industry}\n" |
|
|
response += f"3. It will identify competitors and similar businesses\n\n" |
|
|
response += f"**Currently in your pipeline:**\n" |
|
|
other_in_industry = [p for p in knowledge_base["prospects"] |
|
|
if p.get("industry", "").lower() == industry.lower() and p.get("name") != p_name] |
|
|
if other_in_industry: |
|
|
response += f"Other {industry} prospects:\n" |
|
|
for p in other_in_industry: |
|
|
response += f"- {p.get('name')} (Fit: {p.get('fit_score', 'N/A')})\n" |
|
|
else: |
|
|
response += f"No other {industry} prospects found yet.\n" |
|
|
return history + [[message, response]], "" |
|
|
|
|
|
|
|
|
if any(kw in msg_lower for kw in ["search for new", "find new", "discover new", "look for new"]): |
|
|
response = f"""π **Search for New Prospects** |
|
|
|
|
|
To discover new companies, use the **Prospects Tab**: |
|
|
|
|
|
1. Go to **Prospects** tab |
|
|
2. Enter the number of prospects to find |
|
|
3. Click **"Find Prospects & Contacts"** |
|
|
|
|
|
The AI will: |
|
|
- Search for companies matching {client_name}'s target market |
|
|
- Find decision makers at each company |
|
|
- Draft personalized outreach emails |
|
|
|
|
|
**Currently in your pipeline:** |
|
|
- Prospects: {len(knowledge_base['prospects'])} |
|
|
- Contacts: {len(knowledge_base['contacts'])} |
|
|
- Emails: {len(knowledge_base['emails'])} |
|
|
""" |
|
|
return history + [[message, response]], "" |
|
|
|
|
|
|
|
|
response = get_local_response(message, client_name) |
|
|
return history + [[message, response]], "" |
|
|
|
|
|
|
|
|
def get_local_response(message: str, client_name: str) -> str: |
|
|
"""Handle simple queries locally without AI agent""" |
|
|
msg_lower = message.lower() |
|
|
|
|
|
|
|
|
response = "" |
|
|
|
|
|
|
|
|
if any(kw in msg_lower for kw in ["list prospect", "show prospect", "all prospect", "prospects"]): |
|
|
if knowledge_base["prospects"]: |
|
|
response = f"## π― Prospects for {client_name}\n\n" |
|
|
for i, p in enumerate(knowledge_base["prospects"], 1): |
|
|
response += f"**{i}. {p.get('name', 'Unknown')}**\n" |
|
|
response += f" - Industry: {p.get('industry', 'Unknown')}\n" |
|
|
response += f" - Fit Score: {p.get('fit_score', 'N/A')}/100\n" |
|
|
if p.get('summary'): |
|
|
response += f" - Summary: {p.get('summary', '')[:150]}...\n" if len(p.get('summary', '')) > 150 else f" - Summary: {p.get('summary', '')}\n" |
|
|
response += "\n" |
|
|
else: |
|
|
response = "No prospects discovered yet. Go to the **Discovery** tab and click **Find Prospects & Contacts** to discover potential customers." |
|
|
|
|
|
|
|
|
elif any(kw in msg_lower for kw in ["contact", "decision maker", "who", "email address", "reach"]): |
|
|
|
|
|
specific_prospect = None |
|
|
for p in knowledge_base["prospects"]: |
|
|
if p.get("name", "").lower() in msg_lower: |
|
|
specific_prospect = p |
|
|
break |
|
|
|
|
|
if specific_prospect: |
|
|
prospect_contacts = [c for c in knowledge_base["contacts"] if c.get("company", "").lower() == specific_prospect["name"].lower()] |
|
|
if prospect_contacts: |
|
|
response = f"## π₯ Decision Makers at {specific_prospect['name']}\n\n" |
|
|
for c in prospect_contacts: |
|
|
response += f"**{c.get('name', 'Unknown')}**\n" |
|
|
response += f" - Title: {c.get('title', 'Unknown')}\n" |
|
|
response += f" - Email: {c.get('email', 'Not available')}\n" |
|
|
if c.get('linkedin'): |
|
|
response += f" - LinkedIn: {c.get('linkedin')}\n" |
|
|
response += "\n" |
|
|
else: |
|
|
response = f"No contacts found for **{specific_prospect['name']}** yet." |
|
|
elif knowledge_base["contacts"]: |
|
|
response = f"## π₯ All Decision Makers\n\n" |
|
|
for c in knowledge_base["contacts"]: |
|
|
response += f"**{c.get('name', 'Unknown')}** - {c.get('title', 'Unknown')}\n" |
|
|
response += f" - Company: {c.get('company', 'Unknown')}\n" |
|
|
response += f" - Email: {c.get('email', 'Not available')}\n\n" |
|
|
else: |
|
|
response = "No contacts discovered yet. Run **Find Prospects** to discover decision makers." |
|
|
|
|
|
|
|
|
elif any(kw in msg_lower for kw in ["email", "draft", "outreach", "message"]): |
|
|
specific_prospect = None |
|
|
for p in knowledge_base["prospects"]: |
|
|
if p.get("name", "").lower() in msg_lower: |
|
|
specific_prospect = p |
|
|
break |
|
|
|
|
|
if specific_prospect: |
|
|
prospect_emails = [e for e in knowledge_base["emails"] if specific_prospect["name"].lower() in e.get("prospect_company", "").lower()] |
|
|
if prospect_emails: |
|
|
response = f"## βοΈ Emails for {specific_prospect['name']}\n\n" |
|
|
for e in prospect_emails: |
|
|
response += f"**To:** {e.get('to', 'Unknown')}\n" |
|
|
response += f"**Subject:** {e.get('subject', 'No subject')}\n\n" |
|
|
response += f"```\n{e.get('body', 'No content')}\n```\n\n" |
|
|
else: |
|
|
response = f"No emails drafted for **{specific_prospect['name']}** yet." |
|
|
elif knowledge_base["emails"]: |
|
|
response = "## βοΈ All Drafted Emails\n\n" |
|
|
for e in knowledge_base["emails"]: |
|
|
response += f"**To:** {e.get('to', 'Unknown')} ({e.get('prospect_company', 'Unknown')})\n" |
|
|
response += f"**Subject:** {e.get('subject', 'No subject')}\n\n" |
|
|
else: |
|
|
response = "No emails drafted yet. Run **Find Prospects** to have AI draft outreach emails." |
|
|
|
|
|
|
|
|
elif any(kw in msg_lower for kw in ["tell me about", "describe", "info about", "details", "about"]): |
|
|
specific_prospect = None |
|
|
for p in knowledge_base["prospects"]: |
|
|
if p.get("name", "").lower() in msg_lower: |
|
|
specific_prospect = p |
|
|
break |
|
|
|
|
|
if specific_prospect: |
|
|
response = f"## π’ {specific_prospect['name']}\n\n" |
|
|
response += f"**Industry:** {specific_prospect.get('industry', 'Unknown')}\n" |
|
|
response += f"**Fit Score:** {specific_prospect.get('fit_score', 'N/A')}/100\n\n" |
|
|
if specific_prospect.get('summary'): |
|
|
response += f"**Summary:**\n{specific_prospect.get('summary')}\n\n" |
|
|
if specific_prospect.get('fit_reason'): |
|
|
response += f"**Why they're a good fit:**\n{specific_prospect.get('fit_reason')}\n\n" |
|
|
|
|
|
|
|
|
prospect_contacts = [c for c in knowledge_base["contacts"] if c.get("company", "").lower() == specific_prospect["name"].lower()] |
|
|
if prospect_contacts: |
|
|
response += f"**Decision Makers ({len(prospect_contacts)}):**\n" |
|
|
for c in prospect_contacts: |
|
|
response += f"- {c.get('name', 'Unknown')} - {c.get('title', '')} ({c.get('email', 'no email')})\n" |
|
|
elif knowledge_base["prospects"]: |
|
|
response = "Which prospect would you like to know about?\n\n**Available prospects:**\n" |
|
|
for p in knowledge_base["prospects"]: |
|
|
response += f"- {p.get('name', 'Unknown')}\n" |
|
|
else: |
|
|
response = "No prospects discovered yet. Run **Find Prospects** first." |
|
|
|
|
|
|
|
|
elif any(kw in msg_lower for kw in ["summary", "overview", "status", "pipeline", "how many"]): |
|
|
response = f"## π {client_name} Sales Pipeline Summary\n\n" |
|
|
response += f"| Metric | Count |\n" |
|
|
response += f"|--------|-------|\n" |
|
|
response += f"| Prospects | {len(knowledge_base['prospects'])} |\n" |
|
|
response += f"| Decision Makers | {len(knowledge_base['contacts'])} |\n" |
|
|
response += f"| Emails Drafted | {len(knowledge_base['emails'])} |\n\n" |
|
|
|
|
|
if knowledge_base["prospects"]: |
|
|
response += "**Prospects:**\n" |
|
|
for p in knowledge_base["prospects"]: |
|
|
response += f"- {p.get('name', 'Unknown')} (Fit: {p.get('fit_score', 'N/A')})\n" |
|
|
|
|
|
|
|
|
elif any(kw in msg_lower for kw in ["help", "what can", "how do", "?"]): |
|
|
response = f"""## π¬ {client_name} Sales Assistant |
|
|
|
|
|
I can help you with information about your sales pipeline. Try asking: |
|
|
|
|
|
**About Prospects:** |
|
|
- "List all prospects" |
|
|
- "Tell me about [prospect name]" |
|
|
- "Show prospect details" |
|
|
|
|
|
**About Contacts:** |
|
|
- "Who are the decision makers?" |
|
|
- "Show contacts for [prospect name]" |
|
|
- "List all contacts" |
|
|
|
|
|
**About Emails:** |
|
|
- "Show drafted emails" |
|
|
- "What emails do we have for [prospect name]?" |
|
|
|
|
|
**Pipeline Overview:** |
|
|
- "Give me a summary" |
|
|
- "How many prospects do we have?" |
|
|
- "Pipeline status" |
|
|
""" |
|
|
|
|
|
|
|
|
else: |
|
|
prospects_list = ", ".join([p.get("name", "Unknown") for p in knowledge_base["prospects"]]) if knowledge_base["prospects"] else "None yet" |
|
|
response = f"""I'm not sure what you're asking. Here's what I know: |
|
|
|
|
|
**Current Pipeline:** |
|
|
- Prospects: {len(knowledge_base["prospects"])} ({prospects_list}) |
|
|
- Contacts: {len(knowledge_base["contacts"])} |
|
|
- Emails: {len(knowledge_base["emails"])} |
|
|
|
|
|
Try asking: |
|
|
- "List prospects" |
|
|
- "Tell me about [prospect name]" |
|
|
- "Show contacts" |
|
|
- "Show emails" |
|
|
- "Give me a summary" |
|
|
""" |
|
|
|
|
|
return response |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def generate_handoff_packet(prospect_name: str) -> str: |
|
|
if not prospect_name: |
|
|
return "β οΈ Please select a prospect." |
|
|
|
|
|
prospect = next((p for p in knowledge_base["prospects"] if p["name"] == prospect_name), None) |
|
|
if not prospect: |
|
|
return f"β οΈ Prospect '{prospect_name}' not found." |
|
|
|
|
|
|
|
|
prospect_name_lower = prospect_name.lower() |
|
|
contacts = [c for c in knowledge_base["contacts"] |
|
|
if prospect_name_lower in c.get("company", "").lower() |
|
|
or c.get("company", "").lower() in prospect_name_lower] |
|
|
|
|
|
|
|
|
emails_for_prospect = [e for e in knowledge_base["emails"] |
|
|
if prospect_name_lower in e.get("prospect_company", "").lower() |
|
|
or e.get("prospect_company", "").lower() in prospect_name_lower] |
|
|
email = emails_for_prospect[0] if emails_for_prospect else None |
|
|
|
|
|
|
|
|
if not contacts and email: |
|
|
email_to = email.get("to", "") |
|
|
if email_to: |
|
|
|
|
|
email_body = email.get("body", "") |
|
|
|
|
|
import re |
|
|
name_match = re.search(r'Dear\s+([A-Z][a-z]+)', email_body) |
|
|
contact_name = name_match.group(1) if name_match else email_to.split('@')[0].title() |
|
|
contacts = [{ |
|
|
"name": contact_name, |
|
|
"email": email_to, |
|
|
"title": "Contact", |
|
|
"company": prospect_name |
|
|
}] |
|
|
|
|
|
client_name = knowledge_base["client"]["name"] |
|
|
|
|
|
packet = f"""# π Sales Handoff Packet |
|
|
|
|
|
## {prospect["name"]} |
|
|
|
|
|
**Prepared for:** {client_name} |
|
|
**Date:** {datetime.now().strftime("%Y-%m-%d")} |
|
|
|
|
|
--- |
|
|
|
|
|
## 1. Company Overview |
|
|
|
|
|
{prospect.get("summary", "No summary available.")} |
|
|
|
|
|
**Industry:** {prospect.get("industry", "Unknown")} |
|
|
**Fit Score:** {prospect.get("fit_score", "N/A")}/100 |
|
|
|
|
|
--- |
|
|
|
|
|
## 2. Why They're a Good Fit |
|
|
|
|
|
{prospect.get("fit_reason", "Matches ideal customer profile.")} |
|
|
|
|
|
--- |
|
|
|
|
|
## 3. Decision Makers ({len(contacts)}) |
|
|
|
|
|
""" |
|
|
for c in contacts: |
|
|
packet += f"- **{c.get('name', 'Unknown')}** - {c.get('title', 'Contact')}" |
|
|
if c.get('email'): |
|
|
packet += f" ({c.get('email')})" |
|
|
packet += "\n" |
|
|
|
|
|
if not contacts: |
|
|
packet += "No contacts identified yet.\n" |
|
|
|
|
|
packet += f""" |
|
|
--- |
|
|
|
|
|
## 4. Recommended Approach |
|
|
|
|
|
1. Lead with {client_name}'s value proposition |
|
|
2. Reference their specific challenges |
|
|
3. Propose concrete next step (demo, call) |
|
|
|
|
|
--- |
|
|
|
|
|
## 5. Drafted Email |
|
|
|
|
|
""" |
|
|
if email: |
|
|
packet += f"""**To:** {email.get("to", "N/A")} |
|
|
**Subject:** {email.get("subject", "N/A")} |
|
|
|
|
|
--- |
|
|
|
|
|
{email.get("body", "No email body.")} |
|
|
""" |
|
|
else: |
|
|
packet += "No email drafted yet.\n" |
|
|
|
|
|
packet += f""" |
|
|
--- |
|
|
|
|
|
*Generated by CX AI Agent for {client_name}* |
|
|
""" |
|
|
return packet |
|
|
|
|
|
|
|
|
def get_prospect_choices(): |
|
|
return [p["name"] for p in knowledge_base["prospects"]] if knowledge_base["prospects"] else [] |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def get_logo_base64(): |
|
|
"""Load logo image as base64 for embedding in HTML""" |
|
|
logo_path = Path(__file__).parent / "assets" / "cx_ai_agent_logo_512.png" |
|
|
if logo_path.exists(): |
|
|
with open(logo_path, "rb") as f: |
|
|
return base64.b64encode(f.read()).decode("utf-8") |
|
|
return None |
|
|
|
|
|
def get_favicon_base64(): |
|
|
"""Load favicon as base64 for embedding""" |
|
|
favicon_path = Path(__file__).parent / "assets" / "cx_ai_agent_favicon_32.png" |
|
|
if favicon_path.exists(): |
|
|
with open(favicon_path, "rb") as f: |
|
|
return base64.b64encode(f.read()).decode("utf-8") |
|
|
return None |
|
|
|
|
|
|
|
|
def create_app(): |
|
|
|
|
|
|
|
|
logo_b64 = get_logo_base64() |
|
|
favicon_b64 = get_favicon_base64() |
|
|
|
|
|
|
|
|
sidebar_logo = f'<img src="data:image/png;base64,{logo_b64}" class="sidebar-logo" alt="Logo">' if logo_b64 else '<div class="sidebar-logo" style="background:#0176D3;display:flex;align-items:center;justify-content:center;color:white;font-weight:bold;">CX</div>' |
|
|
|
|
|
|
|
|
favicon_html = f'<link rel="icon" type="image/png" href="data:image/png;base64,{favicon_b64}">' if favicon_b64 else '' |
|
|
|
|
|
head_html = f""" |
|
|
{favicon_html} |
|
|
<meta name="theme-color" content="#0176D3"> |
|
|
<meta name="viewport" content="width=device-width, initial-scale=1.0"> |
|
|
<script> |
|
|
// Sidebar toggle functionality - exposed on window for global access |
|
|
window.toggleSidebar = function() {{ |
|
|
const sidebar = document.querySelector('.sidebar'); |
|
|
const main = document.querySelector('.main-wrapper'); |
|
|
sidebar.classList.toggle('collapsed'); |
|
|
main.classList.toggle('expanded'); |
|
|
}}; |
|
|
|
|
|
window.toggleMobileSidebar = function() {{ |
|
|
const sidebar = document.querySelector('.sidebar'); |
|
|
const overlay = document.querySelector('.sidebar-overlay'); |
|
|
sidebar.classList.toggle('mobile-open'); |
|
|
if (sidebar.classList.contains('mobile-open')) {{ |
|
|
overlay.style.display = 'block'; |
|
|
}} else {{ |
|
|
overlay.style.display = 'none'; |
|
|
}} |
|
|
}}; |
|
|
|
|
|
window.closeMobileSidebar = function() {{ |
|
|
const sidebar = document.querySelector('.sidebar'); |
|
|
const overlay = document.querySelector('.sidebar-overlay'); |
|
|
sidebar.classList.remove('mobile-open'); |
|
|
if (overlay) overlay.style.display = 'none'; |
|
|
}}; |
|
|
|
|
|
// Page navigation using CSS classes |
|
|
window._pageIds = ['setup', 'dashboard', 'discovery', 'prospects', 'contacts', 'emails', 'chat', 'about']; |
|
|
window._pageElementsCache = {{}}; |
|
|
|
|
|
// Find page element - tries multiple approaches |
|
|
function findPageElement(pageId) {{ |
|
|
// Check cache first |
|
|
if (window._pageElementsCache[pageId]) {{ |
|
|
return window._pageElementsCache[pageId]; |
|
|
}} |
|
|
|
|
|
let el = null; |
|
|
|
|
|
// Try direct ID |
|
|
el = document.getElementById('page-' + pageId); |
|
|
|
|
|
// Try querySelector with partial match |
|
|
if (!el) {{ |
|
|
el = document.querySelector('[id*="page-' + pageId + '"]'); |
|
|
}} |
|
|
|
|
|
// Try finding by data attribute |
|
|
if (!el) {{ |
|
|
el = document.querySelector('[data-page="' + pageId + '"]'); |
|
|
}} |
|
|
|
|
|
// Cache if found |
|
|
if (el) {{ |
|
|
window._pageElementsCache[pageId] = el; |
|
|
console.log('Cached page element:', pageId, '->', el.id || el.className); |
|
|
}} |
|
|
|
|
|
return el; |
|
|
}} |
|
|
|
|
|
window.selectPage = function(pageName) {{ |
|
|
console.log('selectPage called:', pageName); |
|
|
|
|
|
// Close mobile sidebar |
|
|
if (window.closeMobileSidebar) {{ |
|
|
window.closeMobileSidebar(); |
|
|
}} |
|
|
|
|
|
// Update active nav item |
|
|
document.querySelectorAll('.nav-item').forEach(function(item) {{ |
|
|
item.classList.toggle('active', item.dataset.page === pageName); |
|
|
}}); |
|
|
|
|
|
// Show/hide pages using class-based approach |
|
|
let foundCount = 0; |
|
|
window._pageIds.forEach(function(id) {{ |
|
|
const el = findPageElement(id); |
|
|
if (el) {{ |
|
|
foundCount++; |
|
|
if (id === pageName) {{ |
|
|
el.classList.remove('page-hidden'); |
|
|
el.style.display = 'flex'; |
|
|
console.log('SHOWING page:', id); |
|
|
}} else {{ |
|
|
el.classList.add('page-hidden'); |
|
|
el.style.display = 'none'; |
|
|
}} |
|
|
}} |
|
|
}}); |
|
|
|
|
|
if (foundCount === 0) {{ |
|
|
console.error('No page elements found! Dumping DOM structure...'); |
|
|
const mainWrapper = document.querySelector('.main-wrapper'); |
|
|
if (mainWrapper) {{ |
|
|
console.log('main-wrapper children:', mainWrapper.children.length); |
|
|
Array.from(mainWrapper.children).forEach(function(child, i) {{ |
|
|
console.log(i + ':', child.tagName, child.id, child.className.substring(0, 50)); |
|
|
}}); |
|
|
}} else {{ |
|
|
console.log('main-wrapper not found!'); |
|
|
}} |
|
|
}} else {{ |
|
|
console.log('Found', foundCount, 'page elements'); |
|
|
}} |
|
|
}}; |
|
|
|
|
|
// Initialize on load |
|
|
document.addEventListener('DOMContentLoaded', function() {{ |
|
|
// Handle overlay click to close sidebar |
|
|
const overlay = document.querySelector('.sidebar-overlay'); |
|
|
if (overlay) {{ |
|
|
overlay.addEventListener('click', window.closeMobileSidebar); |
|
|
}} |
|
|
|
|
|
// Initial page element discovery after Gradio loads |
|
|
setTimeout(function() {{ |
|
|
console.log('Running initial page discovery...'); |
|
|
window.selectPage('setup'); |
|
|
}}, 1000); |
|
|
}}); |
|
|
</script> |
|
|
""" |
|
|
|
|
|
with gr.Blocks( |
|
|
title="CX AI Agent - B2B Sales Intelligence", |
|
|
theme=gr.themes.Soft(primary_hue="blue", secondary_hue="slate", neutral_hue="slate"), |
|
|
css=ENTERPRISE_CSS, |
|
|
head=head_html |
|
|
) as demo: |
|
|
|
|
|
|
|
|
gr.HTML(f""" |
|
|
<!-- Mobile Header --> |
|
|
<div class="mobile-header"> |
|
|
<button class="menu-btn" onclick="window.toggleMobileSidebar()">β°</button> |
|
|
<span class="title">CX AI Agent</span> |
|
|
</div> |
|
|
|
|
|
<!-- Sidebar Overlay (for mobile) --> |
|
|
<div class="sidebar-overlay" onclick="window.closeMobileSidebar()"></div> |
|
|
|
|
|
<!-- Sidebar Navigation --> |
|
|
<div class="sidebar" id="sidebar"> |
|
|
<div class="sidebar-header"> |
|
|
{sidebar_logo} |
|
|
<span class="sidebar-brand">CX AI Agent</span> |
|
|
</div> |
|
|
<button class="toggle-btn" onclick="window.toggleSidebar()">β</button> |
|
|
<nav class="sidebar-nav"> |
|
|
<div class="nav-item active" data-page="setup" onclick="window.selectPage && window.selectPage('setup')"> |
|
|
<span class="nav-icon">βοΈ</span> |
|
|
<span class="nav-text">Setup</span> |
|
|
</div> |
|
|
<div class="nav-item" data-page="dashboard" onclick="window.selectPage && window.selectPage('dashboard')"> |
|
|
<span class="nav-icon">π</span> |
|
|
<span class="nav-text">Dashboard</span> |
|
|
</div> |
|
|
<div class="nav-item" data-page="discovery" onclick="window.selectPage && window.selectPage('discovery')"> |
|
|
<span class="nav-icon">π</span> |
|
|
<span class="nav-text">Discovery</span> |
|
|
</div> |
|
|
<div class="nav-item" data-page="prospects" onclick="window.selectPage && window.selectPage('prospects')"> |
|
|
<span class="nav-icon">π―</span> |
|
|
<span class="nav-text">Prospects</span> |
|
|
</div> |
|
|
<div class="nav-item" data-page="contacts" onclick="window.selectPage && window.selectPage('contacts')"> |
|
|
<span class="nav-icon">π₯</span> |
|
|
<span class="nav-text">Contacts</span> |
|
|
</div> |
|
|
<div class="nav-item" data-page="emails" onclick="window.selectPage && window.selectPage('emails')"> |
|
|
<span class="nav-icon">βοΈ</span> |
|
|
<span class="nav-text">Emails</span> |
|
|
</div> |
|
|
<div class="nav-item" data-page="chat" onclick="window.selectPage && window.selectPage('chat')"> |
|
|
<span class="nav-icon">π¬</span> |
|
|
<span class="nav-text">AI Chat</span> |
|
|
</div> |
|
|
<div class="nav-item" data-page="about" onclick="window.selectPage && window.selectPage('about')"> |
|
|
<span class="nav-icon">βΉοΈ</span> |
|
|
<span class="nav-text">About Us</span> |
|
|
</div> |
|
|
</nav> |
|
|
</div> |
|
|
""") |
|
|
|
|
|
|
|
|
with gr.Column(elem_classes="main-wrapper"): |
|
|
|
|
|
|
|
|
page_selector = gr.Textbox(value="setup", visible=False, elem_id="page-selector") |
|
|
|
|
|
|
|
|
with gr.Row(elem_classes="nav-buttons-row", visible=True): |
|
|
btn_setup = gr.Button("βοΈ Setup", elem_id="btn-setup", size="sm") |
|
|
btn_dashboard = gr.Button("π Dashboard", elem_id="btn-dashboard", size="sm") |
|
|
btn_discovery = gr.Button("π Discovery", elem_id="btn-discovery", size="sm") |
|
|
btn_prospects = gr.Button("π― Prospects", elem_id="btn-prospects", size="sm") |
|
|
btn_contacts = gr.Button("π₯ Contacts", elem_id="btn-contacts", size="sm") |
|
|
btn_emails = gr.Button("βοΈ Emails", elem_id="btn-emails", size="sm") |
|
|
btn_chat = gr.Button("π¬ Chat", elem_id="btn-chat", size="sm") |
|
|
btn_about = gr.Button("βΉοΈ About", elem_id="btn-about", size="sm") |
|
|
|
|
|
|
|
|
with gr.Column(visible=True, elem_id="page-setup") as setup_page: |
|
|
gr.HTML(""" |
|
|
<div class="page-header"> |
|
|
<div> |
|
|
<h1 class="page-title">βοΈ Setup</h1> |
|
|
<p class="page-subtitle">Configure your company and API credentials</p> |
|
|
</div> |
|
|
</div> |
|
|
|
|
|
<div class="info-box"> |
|
|
<span class="info-box-icon">π</span> |
|
|
<div class="info-box-content"> |
|
|
<div class="info-box-title">Getting Started</div> |
|
|
<div class="info-box-text"> |
|
|
Complete these steps to start finding prospects: |
|
|
<ul> |
|
|
<li><strong>HuggingFace Token</strong> - Required for AI-powered research and email drafting</li> |
|
|
<li><strong>Serper API Key</strong> - Optional, enables real-time web search for company info</li> |
|
|
<li><strong>Company Name</strong> - Your company name helps AI find relevant prospects</li> |
|
|
</ul> |
|
|
</div> |
|
|
</div> |
|
|
</div> |
|
|
""") |
|
|
|
|
|
with gr.Row(): |
|
|
with gr.Column(scale=1): |
|
|
gr.HTML("""<div class="form-section"> |
|
|
<h3 style="margin:0 0 12px 0; color: var(--text-primary);">π API Credentials</h3> |
|
|
<p style="color: var(--text-secondary); font-size: 14px; margin-bottom: 16px;"> |
|
|
Enter your HuggingFace token to enable AI features. |
|
|
<a href="https://huggingface.co/settings/tokens" target="_blank">Get a free token β</a> |
|
|
</p> |
|
|
</div>""") |
|
|
|
|
|
hf_token_input = gr.Textbox( |
|
|
label="HuggingFace Token", |
|
|
placeholder="hf_xxxxxxxxxx", |
|
|
type="password" |
|
|
) |
|
|
|
|
|
serper_key_input = gr.Textbox( |
|
|
label="Serper API Key (Optional)", |
|
|
placeholder="For web search - get at serper.dev", |
|
|
type="password" |
|
|
) |
|
|
|
|
|
gr.HTML("""<div class="form-section" style="margin-top: 20px;"> |
|
|
<h3 style="margin:0 0 12px 0; color: var(--text-primary);">π’ Your Company</h3> |
|
|
<p style="color: var(--text-secondary); font-size: 14px; margin-bottom: 16px;"> |
|
|
AI will research your company and find matching prospects. |
|
|
</p> |
|
|
</div>""") |
|
|
|
|
|
client_name_input = gr.Textbox(label="Company Name", placeholder="e.g., Acme Corp") |
|
|
|
|
|
with gr.Row(): |
|
|
setup_btn = gr.Button("π Setup Company", variant="primary", size="lg") |
|
|
reset_btn = gr.Button("ποΈ Reset", variant="stop", size="sm") |
|
|
|
|
|
with gr.Column(scale=2): |
|
|
setup_output = gr.Markdown("*Enter your credentials and company name to begin.*") |
|
|
|
|
|
|
|
|
with gr.Column(visible=True, elem_id="page-dashboard", elem_classes="page-hidden") as dashboard_page: |
|
|
gr.HTML("""<div class="page-header"><div> |
|
|
<h1 class="page-title">π Dashboard</h1> |
|
|
<p class="page-subtitle">Overview of your sales pipeline</p> |
|
|
</div></div> |
|
|
|
|
|
<div class="info-box success"> |
|
|
<span class="info-box-icon">π</span> |
|
|
<div class="info-box-content"> |
|
|
<div class="info-box-title">Pipeline Overview</div> |
|
|
<div class="info-box-text"> |
|
|
Track your progress at a glance. The dashboard shows real-time counts of prospects discovered, contacts found, and emails drafted. Click "Refresh" to update the stats after running Discovery. |
|
|
</div> |
|
|
</div> |
|
|
</div> |
|
|
""") |
|
|
|
|
|
client_status = gr.HTML(get_client_status_html()) |
|
|
|
|
|
gr.HTML('<div class="stats-grid">') |
|
|
with gr.Row(): |
|
|
prospects_stat = gr.HTML(get_stat_html("0", "Prospects Found", "var(--primary-blue)")) |
|
|
contacts_stat = gr.HTML(get_stat_html("0", "Decision Makers", "var(--success-green)")) |
|
|
emails_stat = gr.HTML(get_stat_html("0", "Emails Drafted", "var(--warning-orange)")) |
|
|
gr.HTML(get_stat_html("Qwen3-32B", "AI Model", "var(--purple)")) |
|
|
|
|
|
refresh_btn = gr.Button("π Refresh Dashboard", variant="secondary") |
|
|
|
|
|
|
|
|
with gr.Column(visible=True, elem_id="page-discovery", elem_classes="page-hidden") as discovery_page: |
|
|
gr.HTML("""<div class="page-header"><div> |
|
|
<h1 class="page-title">π Discovery</h1> |
|
|
<p class="page-subtitle">AI-powered prospect discovery</p> |
|
|
</div></div> |
|
|
|
|
|
<div class="info-box tip"> |
|
|
<span class="info-box-icon">π‘</span> |
|
|
<div class="info-box-content"> |
|
|
<div class="info-box-title">How Discovery Works</div> |
|
|
<div class="info-box-text"> |
|
|
<ul> |
|
|
<li><strong>Step 1:</strong> AI searches the web for companies matching your profile</li> |
|
|
<li><strong>Step 2:</strong> Finds decision-makers (CEOs, VPs, Founders) with verified emails</li> |
|
|
<li><strong>Step 3:</strong> Drafts personalized outreach emails for each contact</li> |
|
|
</ul> |
|
|
<em>Tip: Start with 2-3 prospects to test, then increase the number.</em> |
|
|
</div> |
|
|
</div> |
|
|
</div> |
|
|
""") |
|
|
|
|
|
client_status_2 = gr.HTML(get_client_status_html()) |
|
|
|
|
|
with gr.Row(): |
|
|
with gr.Column(scale=1): |
|
|
gr.HTML("""<div class="action-card"> |
|
|
<h3>Find Prospects</h3> |
|
|
<p>AI will search for companies, find decision-makers with verified contacts, and draft personalized emails.</p> |
|
|
</div>""") |
|
|
num_prospects = gr.Slider(minimum=1, maximum=10, value=3, step=1, label="Number of prospects") |
|
|
discover_btn = gr.Button("π Find Prospects & Contacts", variant="primary", size="lg") |
|
|
|
|
|
with gr.Column(scale=2): |
|
|
discovery_output = gr.HTML("<p style='color: var(--text-secondary); font-style: italic;'>Click 'Find Prospects' after completing Setup.</p>") |
|
|
|
|
|
|
|
|
with gr.Column(visible=True, elem_id="page-prospects", elem_classes="page-hidden") as prospects_page: |
|
|
gr.HTML("""<div class="page-header"><div> |
|
|
<h1 class="page-title">π― Prospects</h1> |
|
|
<p class="page-subtitle">Companies discovered by AI</p> |
|
|
</div></div> |
|
|
|
|
|
<div class="info-box"> |
|
|
<span class="info-box-icon">π’</span> |
|
|
<div class="info-box-content"> |
|
|
<div class="info-box-title">Your Prospect Companies</div> |
|
|
<div class="info-box-text"> |
|
|
This list shows all companies found by the AI. Each prospect includes company details, industry, and a fit score (0-100) indicating how well they match your ideal customer profile. Higher scores = better fit! |
|
|
</div> |
|
|
</div> |
|
|
</div> |
|
|
""") |
|
|
refresh_prospects_btn = gr.Button("π Refresh", variant="secondary", size="sm") |
|
|
prospects_list = gr.HTML(get_prospects_html()) |
|
|
|
|
|
|
|
|
with gr.Column(visible=True, elem_id="page-contacts", elem_classes="page-hidden") as contacts_page: |
|
|
gr.HTML("""<div class="page-header"><div> |
|
|
<h1 class="page-title">π₯ Contacts</h1> |
|
|
<p class="page-subtitle">Decision makers found by AI</p> |
|
|
</div></div> |
|
|
|
|
|
<div class="info-box"> |
|
|
<span class="info-box-icon">π€</span> |
|
|
<div class="info-box-content"> |
|
|
<div class="info-box-title">Decision Maker Contacts</div> |
|
|
<div class="info-box-text"> |
|
|
AI finds key decision-makers (CEOs, VPs, Founders, Directors) at each prospect company. Contact info includes name, title, email, and company. Only verified contacts with real email addresses are shown. |
|
|
</div> |
|
|
</div> |
|
|
</div> |
|
|
""") |
|
|
refresh_contacts_btn = gr.Button("π Refresh", variant="secondary", size="sm") |
|
|
contacts_list = gr.HTML(get_contacts_html()) |
|
|
|
|
|
|
|
|
with gr.Column(visible=True, elem_id="page-emails", elem_classes="page-hidden") as emails_page: |
|
|
gr.HTML("""<div class="page-header"><div> |
|
|
<h1 class="page-title">βοΈ Emails</h1> |
|
|
<p class="page-subtitle">AI-drafted outreach emails</p> |
|
|
</div></div> |
|
|
|
|
|
<div class="info-box tip"> |
|
|
<span class="info-box-icon">βοΈ</span> |
|
|
<div class="info-box-content"> |
|
|
<div class="info-box-title">AI-Written Outreach Emails</div> |
|
|
<div class="info-box-text"> |
|
|
Each email is personalized based on the prospect's company, industry, and any pain points discovered during research. Review and customize before sending. Emails are designed to start conversations, not close deals. |
|
|
</div> |
|
|
</div> |
|
|
</div> |
|
|
""") |
|
|
refresh_emails_btn = gr.Button("π Refresh", variant="secondary", size="sm") |
|
|
emails_list = gr.HTML(get_emails_html()) |
|
|
|
|
|
|
|
|
with gr.Column(visible=True, elem_id="page-chat", elem_classes="page-hidden") as chat_page: |
|
|
gr.HTML("""<div class="page-header"><div> |
|
|
<h1 class="page-title">π¬ AI Chat</h1> |
|
|
<p class="page-subtitle">AI-powered communication hub</p> |
|
|
</div></div>""") |
|
|
|
|
|
with gr.Tabs(elem_classes="chat-subtabs"): |
|
|
|
|
|
with gr.Tab("π― Sales Assistant", elem_id="tab-sales-assistant"): |
|
|
gr.HTML(""" |
|
|
<div class="info-box success"> |
|
|
<span class="info-box-icon">π€</span> |
|
|
<div class="info-box-content"> |
|
|
<div class="info-box-title">Your AI Sales Assistant</div> |
|
|
<div class="info-box-text"> |
|
|
Chat with AI to research companies, draft emails, get talking points, or manage your pipeline. The AI has access to all your prospect data and can perform web searches for real-time info. |
|
|
</div> |
|
|
</div> |
|
|
</div> |
|
|
""") |
|
|
|
|
|
chatbot = gr.Chatbot(value=[], height=350, label="Sales Assistant Chat") |
|
|
|
|
|
with gr.Row(): |
|
|
chat_input = gr.Textbox( |
|
|
label="Message", |
|
|
placeholder="Ask about prospects, search for companies, draft emails...", |
|
|
lines=1, |
|
|
scale=4 |
|
|
) |
|
|
send_btn = gr.Button("Send", variant="primary", scale=1) |
|
|
|
|
|
gr.HTML("""<div class="action-card" style="margin-top: 16px;"> |
|
|
<h4>π‘ Try These Prompts</h4> |
|
|
<ul style="font-size: 13px; line-height: 1.8; margin: 8px 0 0 0; padding-left: 20px;"> |
|
|
<li>"Search for DTC fashion brands that raised Series A"</li> |
|
|
<li>"Draft an email to the CEO of Warby Parker"</li> |
|
|
<li>"Give me talking points for my call with Glossier"</li> |
|
|
<li>"Summary of all prospects and their status"</li> |
|
|
</ul> |
|
|
</div>""") |
|
|
|
|
|
|
|
|
with gr.Tab("π€ Prospect Chat Demo", elem_id="tab-prospect-chat"): |
|
|
gr.HTML(""" |
|
|
<div class="info-box tip"> |
|
|
<span class="info-box-icon">π¬</span> |
|
|
<div class="info-box-content"> |
|
|
<div class="info-box-title">Prospect Communication Demo</div> |
|
|
<div class="info-box-text"> |
|
|
This demonstrates how prospects can interact with your company's AI assistant. The AI can answer questions about your products/services, qualify leads, schedule meetings, and escalate to human agents when needed. |
|
|
</div> |
|
|
</div> |
|
|
</div> |
|
|
""") |
|
|
|
|
|
prospect_chatbot = gr.Chatbot( |
|
|
value=[], |
|
|
height=350, |
|
|
label="Prospect Chat", |
|
|
avatar_images=(None, "https://api.dicebear.com/7.x/bottts/svg?seed=cx-agent") |
|
|
) |
|
|
|
|
|
with gr.Row(): |
|
|
prospect_input = gr.Textbox( |
|
|
label="Prospect Message", |
|
|
placeholder="Hi, I'm interested in learning more about your services...", |
|
|
lines=1, |
|
|
scale=4 |
|
|
) |
|
|
prospect_send_btn = gr.Button("Send", variant="primary", scale=1) |
|
|
|
|
|
with gr.Row(): |
|
|
with gr.Column(scale=2): |
|
|
gr.HTML("""<div class="action-card"> |
|
|
<h4>π Demo Scenario</h4> |
|
|
<p style="font-size: 13px; margin-bottom: 8px;">You are a prospect visiting the client's website. The AI will:</p> |
|
|
<ul style="font-size: 13px; line-height: 1.6; margin: 0; padding-left: 20px;"> |
|
|
<li>Answer questions about products and services</li> |
|
|
<li>Qualify you as a lead based on your needs</li> |
|
|
<li>Offer to schedule a meeting with sales</li> |
|
|
<li>Escalate complex inquiries to human agents</li> |
|
|
</ul> |
|
|
</div>""") |
|
|
|
|
|
with gr.Column(scale=1): |
|
|
gr.HTML("""<div class="action-card"> |
|
|
<h4>β‘ Quick Actions</h4> |
|
|
</div>""") |
|
|
generate_handoff_btn = gr.Button("π Generate Handoff Packet", variant="secondary", size="sm") |
|
|
escalate_btn = gr.Button("π¨ Escalate to Human", variant="stop", size="sm") |
|
|
schedule_btn = gr.Button("π
Schedule Meeting", variant="secondary", size="sm") |
|
|
|
|
|
handoff_output = gr.Markdown(visible=False, elem_classes="handoff-packet") |
|
|
|
|
|
|
|
|
with gr.Column(visible=True, elem_id="page-about", elem_classes="page-hidden") as about_page: |
|
|
gr.HTML("""<div class="page-header"><div> |
|
|
<h1 class="page-title">βΉοΈ About Us</h1> |
|
|
<p class="page-subtitle">Learn more about CX AI Agent</p> |
|
|
</div></div>""") |
|
|
|
|
|
gr.Markdown(""" |
|
|
# π€ CX AI Agent - B2B Sales Intelligence Platform |
|
|
|
|
|
[](https://github.com) |
|
|
[](https://huggingface.co) |
|
|
[](https://gradio.app) |
|
|
|
|
|
> **π MCP in Action Track - Enterprise Applications** |
|
|
> |
|
|
> Tag: `mcp-in-action-track-enterprise` |
|
|
|
|
|
--- |
|
|
|
|
|
## π Overview |
|
|
|
|
|
**CX AI Agent** is an AI-powered B2B sales automation platform that helps sales teams discover prospects, find decision-makers, and draft personalized outreach emailsβall powered by autonomous AI agents using the Model Context Protocol (MCP). |
|
|
|
|
|
### π― Key Features |
|
|
|
|
|
| Feature | Description | |
|
|
|---------|-------------| |
|
|
| **π AI Discovery** | Automatically find and research prospect companies matching your ideal customer profile | |
|
|
| **π₯ Contact Finder** | Locate decision-makers (CEOs, VPs, Founders) with verified email addresses | |
|
|
| **βοΈ Email Drafting** | Generate personalized cold outreach emails based on company research | |
|
|
| **π¬ AI Chat** | Interactive assistant for pipeline management and real-time research | |
|
|
| **π€ Prospect Chat** | Demo of prospect-facing AI with handoff & escalation capabilities | |
|
|
| **π Dashboard** | Real-time pipeline metrics and progress tracking | |
|
|
|
|
|
--- |
|
|
|
|
|
## ποΈ Architecture |
|
|
|
|
|
``` |
|
|
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ |
|
|
β CX AI Agent β |
|
|
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ€ |
|
|
β βββββββββββββββ βββββββββββββββ βββββββββββββββ β |
|
|
β β Gradio β β Autonomousβ β MCP β β |
|
|
β β UI ββββ Agent ββββ Servers β β |
|
|
β βββββββββββββββ βββββββββββββββ βββββββββββββββ β |
|
|
β β β β β |
|
|
β βΌ βΌ βΌ β |
|
|
β βββββββββββββββββββββββββββββββββββββββββββββββββββ β |
|
|
β β MCP Tool Definitions β β |
|
|
β β β’ Search (Web, News) β β |
|
|
β β β’ Store (Prospects, Contacts, Facts) β β |
|
|
β β β’ Email (Send, Thread Management) β β |
|
|
β β β’ Calendar (Meeting Slots, Invites) β β |
|
|
β βββββββββββββββββββββββββββββββββββββββββββββββββββ β |
|
|
ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ |
|
|
``` |
|
|
|
|
|
--- |
|
|
|
|
|
## π Getting Started |
|
|
|
|
|
### Prerequisites |
|
|
|
|
|
- Python 3.8+ |
|
|
- HuggingFace API Token ([Get one free](https://huggingface.co/settings/tokens)) |
|
|
- Serper API Key (Optional, for web search) |
|
|
|
|
|
### Quick Start |
|
|
|
|
|
1. **Setup**: Enter your API credentials and company name |
|
|
2. **Discover**: Let AI find prospects matching your profile |
|
|
3. **Review**: Check discovered companies and contacts |
|
|
4. **Engage**: Use AI-drafted emails for outreach |
|
|
|
|
|
--- |
|
|
|
|
|
## π§ MCP Tools Available |
|
|
|
|
|
### Search MCP Server |
|
|
- `search_web` - Search the web for company information |
|
|
- `search_news` - Find recent news about companies |
|
|
|
|
|
### Store MCP Server |
|
|
- `save_prospect` / `get_prospect` / `list_prospects` - Manage prospects |
|
|
- `save_company` / `get_company` - Store company data |
|
|
- `save_contact` / `list_contacts_by_domain` - Manage contacts |
|
|
- `save_fact` - Store research insights |
|
|
- `discover_prospects_with_contacts` - Full discovery pipeline |
|
|
- `find_verified_contacts` - Find decision-makers |
|
|
- `check_suppression` - Compliance checking |
|
|
|
|
|
### Email MCP Server |
|
|
- `send_email` - Send outreach emails |
|
|
- `get_email_thread` - Retrieve conversation history |
|
|
|
|
|
### Calendar MCP Server |
|
|
- `suggest_meeting_slots` - Generate available times |
|
|
- `generate_calendar_invite` - Create .ics files |
|
|
|
|
|
--- |
|
|
|
|
|
## π Prospect Chat Demo |
|
|
|
|
|
The **Prospect Chat Demo** tab showcases how prospects can interact with your company's AI: |
|
|
|
|
|
- **Lead Qualification**: AI asks qualifying questions to understand prospect needs |
|
|
- **Handoff Packets**: Generate comprehensive summaries for human sales reps |
|
|
- **Escalation Flows**: Automatically escalate complex inquiries to humans |
|
|
- **Meeting Scheduling**: Integrate with calendar for instant booking |
|
|
|
|
|
--- |
|
|
|
|
|
## π Technology Stack |
|
|
|
|
|
| Component | Technology | |
|
|
|-----------|------------| |
|
|
| **Frontend** | Gradio 5.x | |
|
|
| **AI Model** | Qwen3-32B via HuggingFace | |
|
|
| **Protocol** | Model Context Protocol (MCP) | |
|
|
| **Search** | Serper API | |
|
|
| **Language** | Python 3.8+ | |
|
|
|
|
|
--- |
|
|
|
|
|
## π License |
|
|
|
|
|
This project is open source and available under the MIT License. |
|
|
|
|
|
--- |
|
|
|
|
|
## π Acknowledgments |
|
|
|
|
|
- **Anthropic** - Model Context Protocol specification |
|
|
- **HuggingFace** - AI model hosting and inference |
|
|
- **Gradio** - UI framework |
|
|
- **Serper** - Web search API |
|
|
|
|
|
--- |
|
|
|
|
|
## π¨βπ» Developer |
|
|
|
|
|
**Syed Muzakkir Hussain** |
|
|
|
|
|
[](https://huggingface.co/muzakkirhussain011) |
|
|
|
|
|
[https://huggingface.co/muzakkirhussain011](https://huggingface.co/muzakkirhussain011) |
|
|
|
|
|
--- |
|
|
|
|
|
<div align="center"> |
|
|
|
|
|
**Built with β€οΈ by [Syed Muzakkir Hussain](https://huggingface.co/muzakkirhussain011) for the Gradio Agents & MCP Hackathon 2025** |
|
|
|
|
|
`mcp-in-action-track-enterprise` |
|
|
|
|
|
</div> |
|
|
""") |
|
|
|
|
|
|
|
|
gr.HTML(""" |
|
|
<div class="footer"> |
|
|
<p><strong>CX AI Agent</strong> β Automated B2B Sales Intelligence</p> |
|
|
<p style="font-size: 12px;">Powered by AI β’ Β© 2025</p> |
|
|
</div> |
|
|
""") |
|
|
|
|
|
|
|
|
|
|
|
all_pages = [setup_page, dashboard_page, discovery_page, prospects_page, contacts_page, emails_page, chat_page, about_page] |
|
|
|
|
|
def show_page(page_name): |
|
|
"""Return visibility updates for all pages""" |
|
|
pages = { |
|
|
"setup": [True, False, False, False, False, False, False, False], |
|
|
"dashboard": [False, True, False, False, False, False, False, False], |
|
|
"discovery": [False, False, True, False, False, False, False, False], |
|
|
"prospects": [False, False, False, True, False, False, False, False], |
|
|
"contacts": [False, False, False, False, True, False, False, False], |
|
|
"emails": [False, False, False, False, False, True, False, False], |
|
|
"chat": [False, False, False, False, False, False, True, False], |
|
|
"about": [False, False, False, False, False, False, False, True], |
|
|
} |
|
|
visibility = pages.get(page_name, pages["setup"]) |
|
|
return [gr.update(visible=v) for v in visibility] |
|
|
|
|
|
|
|
|
page_selector.change(fn=show_page, inputs=[page_selector], outputs=all_pages) |
|
|
|
|
|
|
|
|
btn_setup.click(fn=lambda: show_page("setup"), outputs=all_pages) |
|
|
btn_dashboard.click(fn=lambda: show_page("dashboard"), outputs=all_pages) |
|
|
btn_discovery.click(fn=lambda: show_page("discovery"), outputs=all_pages) |
|
|
btn_prospects.click(fn=lambda: show_page("prospects"), outputs=all_pages) |
|
|
btn_contacts.click(fn=lambda: show_page("contacts"), outputs=all_pages) |
|
|
btn_emails.click(fn=lambda: show_page("emails"), outputs=all_pages) |
|
|
btn_chat.click(fn=lambda: show_page("chat"), outputs=all_pages) |
|
|
btn_about.click(fn=lambda: show_page("about"), outputs=all_pages) |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
setup_btn.click( |
|
|
fn=setup_client_company, |
|
|
inputs=[client_name_input, hf_token_input, serper_key_input], |
|
|
outputs=[setup_output] |
|
|
).then( |
|
|
fn=lambda: (get_client_status_html(), get_client_status_html()), |
|
|
outputs=[client_status, client_status_2] |
|
|
) |
|
|
|
|
|
reset_btn.click( |
|
|
fn=reset_all_data, |
|
|
outputs=[prospects_stat, contacts_stat, emails_stat, client_status, prospects_list, emails_list, |
|
|
contacts_list, client_name_input, setup_output, discovery_output] |
|
|
) |
|
|
|
|
|
def refresh_dashboard(): |
|
|
stats = get_dashboard_stats() |
|
|
return stats[0], stats[1], stats[2], stats[3] |
|
|
|
|
|
refresh_btn.click(fn=refresh_dashboard, outputs=[prospects_stat, contacts_stat, emails_stat, client_status]) |
|
|
|
|
|
|
|
|
discover_btn.click( |
|
|
fn=discover_prospects, |
|
|
inputs=[num_prospects], |
|
|
outputs=[discovery_output] |
|
|
).then( |
|
|
fn=lambda: (get_prospects_html(), get_contacts_html(), get_emails_html()), |
|
|
outputs=[prospects_list, contacts_list, emails_list] |
|
|
).then( |
|
|
fn=refresh_dashboard, |
|
|
outputs=[prospects_stat, contacts_stat, emails_stat, client_status] |
|
|
) |
|
|
|
|
|
refresh_prospects_btn.click(fn=get_prospects_html, outputs=[prospects_list]) |
|
|
refresh_contacts_btn.click(fn=get_contacts_html, outputs=[contacts_list]) |
|
|
refresh_emails_btn.click(fn=get_emails_html, outputs=[emails_list]) |
|
|
|
|
|
|
|
|
async def chat_async_wrapper(message, history): |
|
|
token = session_hf_token.get("token", "") |
|
|
final_result = (history, "") |
|
|
async for result in chat_with_ai_async(message, history, token): |
|
|
final_result = result |
|
|
return final_result |
|
|
|
|
|
send_btn.click(fn=chat_async_wrapper, inputs=[chat_input, chatbot], outputs=[chatbot, chat_input]) |
|
|
chat_input.submit(fn=chat_async_wrapper, inputs=[chat_input, chatbot], outputs=[chatbot, chat_input]) |
|
|
|
|
|
|
|
|
|
|
|
async def prospect_chat_wrapper(message, history): |
|
|
"""Handle prospect-facing chat with company representative AI""" |
|
|
if not message.strip(): |
|
|
return history, "" |
|
|
|
|
|
|
|
|
client_info = knowledge_base["client"].get("name") or "Our Company" |
|
|
|
|
|
|
|
|
system_context = f"""You are an AI assistant representing {client_info}. You are speaking with a potential prospect who is interested in learning about the company's products and services. |
|
|
|
|
|
Your role is to: |
|
|
1. Answer questions about the company professionally and helpfully |
|
|
2. Qualify the prospect by understanding their needs, company size, and timeline |
|
|
3. Offer to schedule meetings with sales representatives when appropriate |
|
|
4. Escalate complex technical or pricing questions to human agents |
|
|
|
|
|
Be friendly, professional, and helpful. Focus on understanding the prospect's needs.""" |
|
|
|
|
|
history = history + [[message, None]] |
|
|
|
|
|
|
|
|
token = session_hf_token.get("token", "") |
|
|
if token: |
|
|
try: |
|
|
from huggingface_hub import InferenceClient |
|
|
client = InferenceClient(token=token) |
|
|
|
|
|
messages = [{"role": "system", "content": system_context}] |
|
|
for h in history[:-1]: |
|
|
if h[0]: |
|
|
messages.append({"role": "user", "content": h[0]}) |
|
|
if h[1]: |
|
|
messages.append({"role": "assistant", "content": h[1]}) |
|
|
messages.append({"role": "user", "content": message}) |
|
|
|
|
|
response = client.chat_completion( |
|
|
model="Qwen/Qwen2.5-72B-Instruct", |
|
|
messages=messages, |
|
|
max_tokens=500 |
|
|
) |
|
|
reply = response.choices[0].message.content |
|
|
except Exception as e: |
|
|
reply = f"I apologize, I'm having trouble connecting right now. Please try again or contact us directly. (Error: {str(e)[:50]})" |
|
|
else: |
|
|
reply = f"Thank you for your interest in {client_info}! I'd be happy to help you learn more about our solutions. What specific challenges are you looking to address?" |
|
|
|
|
|
history[-1][1] = reply |
|
|
return history, "" |
|
|
|
|
|
def generate_handoff_packet(chat_history): |
|
|
"""Generate a handoff packet from the prospect conversation""" |
|
|
if not chat_history: |
|
|
return gr.update(visible=True, value="**β οΈ No conversation to generate handoff from.** Start a conversation first.") |
|
|
|
|
|
|
|
|
conversation_text = "\n".join([f"Prospect: {h[0]}\nAgent: {h[1]}" for h in chat_history if h[0] and h[1]]) |
|
|
|
|
|
client_name = knowledge_base["client"].get("name") or "Unknown Client" |
|
|
|
|
|
packet = f""" |
|
|
## π Handoff Packet |
|
|
|
|
|
**Generated:** {datetime.now().strftime("%Y-%m-%d %H:%M")} |
|
|
**Client Company:** {client_name} |
|
|
|
|
|
--- |
|
|
|
|
|
### π Conversation Summary |
|
|
|
|
|
{len(chat_history)} messages exchanged with prospect. |
|
|
|
|
|
### π¬ Full Conversation Log |
|
|
|
|
|
``` |
|
|
{conversation_text[:1500]}{'...' if len(conversation_text) > 1500 else ''} |
|
|
``` |
|
|
|
|
|
### π― Recommended Actions |
|
|
|
|
|
1. Review conversation for prospect pain points |
|
|
2. Prepare personalized follow-up materials |
|
|
3. Schedule discovery call within 24-48 hours |
|
|
|
|
|
### π Lead Score: Pending Assessment |
|
|
|
|
|
--- |
|
|
|
|
|
*This packet was auto-generated by CX AI Agent* |
|
|
""" |
|
|
return gr.update(visible=True, value=packet) |
|
|
|
|
|
def escalate_to_human(chat_history): |
|
|
"""Escalate conversation to human agent""" |
|
|
if not chat_history: |
|
|
return gr.update(visible=True, value="**π¨ Escalation Created**\n\nNo conversation history to escalate. A human agent will reach out to assist you.") |
|
|
|
|
|
return gr.update(visible=True, value=f""" |
|
|
## π¨ Escalation Created |
|
|
|
|
|
**Status:** Pending Human Review |
|
|
**Priority:** High |
|
|
**Timestamp:** {datetime.now().strftime("%Y-%m-%d %H:%M")} |
|
|
|
|
|
A human sales representative will review this conversation and reach out shortly. |
|
|
|
|
|
**Messages in thread:** {len(chat_history)} |
|
|
""") |
|
|
|
|
|
def schedule_meeting(): |
|
|
"""Generate meeting scheduling info""" |
|
|
from datetime import timedelta |
|
|
now = datetime.now() |
|
|
slots = [] |
|
|
for i in range(1, 4): |
|
|
day = now + timedelta(days=i) |
|
|
if day.weekday() < 5: |
|
|
slots.append(f"- {day.strftime('%A, %B %d')} at 10:00 AM EST") |
|
|
slots.append(f"- {day.strftime('%A, %B %d')} at 2:00 PM EST") |
|
|
|
|
|
return gr.update(visible=True, value=f""" |
|
|
## π
Meeting Scheduling |
|
|
|
|
|
**Available Time Slots:** |
|
|
|
|
|
{chr(10).join(slots[:4])} |
|
|
|
|
|
To schedule a meeting, please reply with your preferred time slot, or [click here](#) to access our calendar booking system. |
|
|
|
|
|
*Times shown in EST. Meetings are typically 30 minutes.* |
|
|
""") |
|
|
|
|
|
|
|
|
prospect_send_btn.click( |
|
|
fn=prospect_chat_wrapper, |
|
|
inputs=[prospect_input, prospect_chatbot], |
|
|
outputs=[prospect_chatbot, prospect_input] |
|
|
) |
|
|
prospect_input.submit( |
|
|
fn=prospect_chat_wrapper, |
|
|
inputs=[prospect_input, prospect_chatbot], |
|
|
outputs=[prospect_chatbot, prospect_input] |
|
|
) |
|
|
|
|
|
|
|
|
generate_handoff_btn.click(fn=generate_handoff_packet, inputs=[prospect_chatbot], outputs=[handoff_output]) |
|
|
escalate_btn.click(fn=escalate_to_human, inputs=[prospect_chatbot], outputs=[handoff_output]) |
|
|
schedule_btn.click(fn=schedule_meeting, outputs=[handoff_output]) |
|
|
|
|
|
return demo |
|
|
|
|
|
|
|
|
if __name__ == "__main__": |
|
|
demo = create_app() |
|
|
demo.launch(server_name="0.0.0.0", server_port=7860, show_error=True) |
|
|
|