Trong bài viết này, mình sẽ chia sẻ chi tiết cách xây dựng một hệ thống AI Sales Assistant hoàn chỉnh, bao gồm hai tính năng cốt lõi: Lead Scoring (chấm điểm tiềm năng) và Auto Email Writer (tự động viết email). Toàn bộ demo sử dụng HolySheep AI — nền tảng API AI với chi phí chỉ bằng 15% so với OpenAI.
Nghiên cứu điển hình: Startup AI tại TP.HCM tăng 6x doanh thu
Bối cảnh: Một startup platform thương mại điện tử tại TP.HCM với đội ngũ sales 12 người, xử lý trung bình 500-800 lead mới mỗi ngày. Đội ngũ này dành tới 70% thời gian chỉ để đọc thông tin khách hàng và viết email phản hồi — thay vì closing deal.
Điểm đau với nhà cung cấp cũ: Họ đã thử dùng OpenAI API trong 6 tháng nhưng gặp phải:
- Chi phí hóa đơn hàng tháng: $4,200 USD cho 45 triệu tokens
- Độ trễ trung bình: 1.8 - 2.3 giây cho mỗi API call
- Tốc độ xử lý batch 500 leads: 45 phút
- Rate limiting liên tục vào giờ cao điểm
Lý do chọn HolySheep: Sau khi benchmark 3 nhà cung cấp, đội ngũ kỹ thuật chọn HolySheep AI vì:
- Giá chỉ $0.42/MTok với DeepSeek V3.2 (rẻ hơn 85% so với GPT-4.1)
- Hỗ trợ WeChat/Alipay cho người dùng châu Á
- Tín dụng miễn phí khi đăng ký để test
- Độ trễ thực tế <50ms tại server châu Á
Kết quả sau 30 ngày go-live:
- Độ trễ trung bình: 420ms → 180ms (giảm 57%)
- Hóa đơn hàng tháng: $4,200 → $680 USD (tiết kiệm 84%)
- Thời gian xử lý batch: 45 phút → 8 phút
- Tỷ lệ phản hồi lead trong 5 phút: 12% → 68%
Kiến trúc hệ thống tổng quan
┌─────────────────────────────────────────────────────────────┐
│ AI SALES ASSISTANT │
├─────────────────────────────────────────────────────────────┤
│ ┌──────────────┐ ┌──────────────┐ ┌──────────────┐ │
│ │ Lead Ingest │───▶│ Lead Scoring │───▶│ Email Writer │ │
│ │ Service │ │ Engine │ │ Engine │ │
│ └──────────────┘ └──────────────┘ └──────────────┘ │
│ │ │ │ │
│ ▼ ▼ ▼ │
│ ┌─────────────────────────────────────────────────────┐ │
│ │ HolySheep AI API │ │
│ │ base_url: https://api.holysheep.ai/v1 │ │
│ │ Model: DeepSeek V3.2 ($0.42/MTok) │ │
│ └─────────────────────────────────────────────────────┘ │
│ │ │
│ ▼ │
│ ┌──────────────┐ ┌──────────────┐ ┌──────────────┐ │
│ │ Database │ │ Queue │ │ Email SMTP │ │
│ └──────────────┘ └──────────────┘ └──────────────┘ │
└─────────────────────────────────────────────────────────────┘
Module 1: Lead Scoring Engine — Chấm điểm tiềm năng khách hàng
Lead scoring là việc phân loại khách hàng tiềm năng theo điểm số (0-100) dựa trên hành vi, thông tin công ty, và tín hiệu mua hàng. Dưới đây là code production-ready sử dụng HolySheep AI:
import requests
import json
from dataclasses import dataclass
from typing import List, Dict
@dataclass
class Lead:
company_name: str
industry: str
employee_count: int
website_traffic: int
email_opens: int
page_views: int
demo_requests: int
source: str # 'organic', 'paid', 'referral', 'cold_outreach'
class LeadScoringEngine:
def __init__(self, api_key: str):
self.base_url = "https://api.holysheep.ai/v1"
self.headers = {
"Authorization": f"Bearer {api_key}",
"Content-Type": "application/json"
}
def score_lead(self, lead: Lead) -> Dict:
"""
Chấm điểm lead sử dụng AI với scoring criteria:
- Company Fit (30 điểm): ngành, quy mô phù hợp
- Engagement (40 điểm): hành vi trên website
- Intent Signals (30 điểm): email, demo request
"""
prompt = f"""Bạn là chuyên gia B2B Sales. Chấm điểm lead sau (0-100):
THÔNG TIN CÔNG TY:
- Tên công ty: {lead.company_name}
- Ngành: {lead.industry}
- Số nhân viên: {lead.employee_count}
- Traffic website/tháng: {lead.website_traffic}
TÍNH HIỆU HÀNH VI:
- Email mở: {lead.email_opens}
- Page views: {lead.page_views}
- Demo request: {lead.demo_requests}
- Nguồn: {lead.source}
Trả về JSON format:
{{
"score": [0-100],
"tier": "A|B|C|D",
"reasoning": "[giải thích ngắn]",
"priority": "hot|warm|cold",
"recommended_action": "[hành động cụ thể]"
}}
"""
payload = {
"model": "deepseek-chat",
"messages": [
{"role": "system", "content": "Bạn là chuyên gia B2B Sales với 10 năm kinh nghiệm. Chỉ trả về JSON."},
{"role": "user", "content": prompt}
],
"temperature": 0.3, # Low temp cho scoring nhất quán
"max_tokens": 500
}
response = requests.post(
f"{self.base_url}/chat/completions",
headers=self.headers,
json=payload
)
result = response.json()
return json.loads(result['choices'][0]['message']['content'])
def batch_score_leads(self, leads: List[Lead], batch_size: int = 10) -> List[Dict]:
"""
Xử lý batch leads với rate limiting thông minh
"""
results = []
for i in range(0, len(leads), batch_size):
batch = leads[i:i+batch_size]
for lead in batch:
try:
score = self.score_lead(lead)
score['lead_data'] = {
'company': lead.company_name,
'industry': lead.industry
}
results.append(score)
except Exception as e:
print(f"Lỗi scoring {lead.company_name}: {e}")
results.append({
'score': 0,
'tier': 'D',
'error': str(e)
})
return results
Sử dụng
scorer = LeadScoringEngine(api_key="YOUR_HOLYSHEEP_API_KEY")
sample_lead = Lead(
company_name="Công ty TNHH Giải Pháp Số Miền Nam",
industry="Software/IT",
employee_count=150,
website_traffic=15000,
email_opens=12,
page_views=35,
demo_requests=1,
source="paid"
)
result = scorer.score_lead(sample_lead)
print(f"Điểm: {result['score']} | Tier: {result['tier']} | Ưu tiên: {result['priority']}")
Output: Điểm: 78 | Tier: A | Ưu tiên: hot
Phân tích chi phí thực tế:
- Mỗi scoring call sử dụng ~800 tokens input + ~150 tokens output
- Với 500 leads/ngày: 500 × 0.00095 MTok × $0.42 = $0.20/ngày
- So với OpenAI GPT-4: 500 × 0.00095 × $8 = $3.80/ngày
- Tiết kiệm: 95% chi phí scoring
Module 2: Auto Email Writer — Tự động viết email cá nhân hóa
Tính năng thứ hai là tự động viết email phản hồi dựa trên thông tin lead và context cuộc hội thoại. Mình sẽ xây dựng một engine với 5 templates email và khả năng personalization cao:
import requests
import time
from enum import Enum
from typing import Optional
class EmailTemplate(Enum):
INITIAL_OUTREACH = "initial_outreach"
FOLLOW_UP_1 = "follow_up_1"
FOLLOW_UP_2 = "follow_up_2"
DEMO_INVITATION = "demo_invitation"
OBJECTION_HANDLING = "objection_handling"
class EmailWriterEngine:
def __init__(self, api_key: str):
self.base_url = "https://api.holysheep.ai/v1"
self.headers = {
"Authorization": f"Bearer {api_key}",
"Content-Type": "application/json"
}
def generate_email(
self,
lead_info: dict,
template: EmailTemplate,
tone: str = "professional",
max_length: int = 200
) -> dict:
"""
Sinh email tự động với context đầy đủ
"""
template_prompts = {
EmailTemplate.INITIAL_OUTREACH: """Viết email chào hàng initial outreach.
- Ngắn gọn, giá trị rõ ràng
- Có personalized hook dựa trên thông tin công ty""",
EmailTemplate.FOLLOW_UP_1: """Viết email follow-up lần 1.
- Nhắc nhở nhẹ nhàng
- Thêm value mới
- Call-to-action cụ thể""",
EmailTemplate.FOLLOW_UP_2: """Viết email follow-up lần 2.
- FOMO trigger
- Offer deadline
- Break-up email option""",
EmailTemplate.DEMO_INVITATION: """Viết email mời demo.
- Nêu rõ lợi ích demo
- Calendar link placeholder
- 3 thời gian gợi ý""",
EmailTemplate.OBJECTION_HANDLING: """Viết email xử lý objection.
- Đồng cảm trước
- Reframe giá trị
- Offer trial/alternative"""
}
system_prompt = f"""Bạn là Senior B2B Sales Copywriter với 8 năm kinh nghiệm.
Viết email có:
- Tone: {tone}
- Subject line: hấp dẫn, dưới 50 ký tự
- Body: ngắn gọn dưới {max_length} từ, 3-4 sentences
- Signature: professional, không cần tên
- CTA: rõ ràng, 1 action duy nhất
Format trả về:
---
SUBJECT: [subject line]
BODY: [email body]
---
"""
user_prompt = f"""{template_prompts[template]}
THÔNG TIN LEAD:
- Tên công ty: {lead_info.get('company_name', 'N/A')}
- Ngành: {lead_info.get('industry', 'N/A')}
- Quy mô: {lead_info.get('employee_count', 'N/A')} nhân viên
- Website: {lead_info.get('website', 'N/A')}
- Pain point đã mention: {lead_info.get('pain_point', 'Không có')}
- Đã dùng competitor: {lead_info.get('competitor', 'Không')}
- Lead score: {lead_info.get('score', 'N/A')}/100
"""
payload = {
"model": "deepseek-chat",
"messages": [
{"role": "system", "content": system_prompt},
{"role": "user", "content": user_prompt}
],
"temperature": 0.7, # Higher temp cho creative writing
"max_tokens": 800
}
start_time = time.time()
response = requests.post(
f"{self.base_url}/chat/completions",
headers=self.headers,
json=payload
)
latency_ms = (time.time() - start_time) * 1000
content = response.json()['choices'][0]['message']['content']
# Parse output
lines = content.split('\n')
subject = ""
body = ""
in_body = False
for line in lines:
if line.startswith('SUBJECT:'):
subject = line.replace('SUBJECT:', '').strip()
elif line.startswith('BODY:'):
in_body = True
body = line.replace('BODY:', '').strip()
elif in_body and line.strip():
body += '\n' + line.strip()
return {
"subject": subject,
"body": body,
"template_used": template.value,
"latency_ms": round(latency_ms, 2),
"tokens_used": response.json().get('usage', {}).get('total_tokens', 0)
}
def batch_generate(
self,
leads_data: list,
template: EmailTemplate
) -> list:
"""
Batch generate emails với rate limit protection
Limit: 60 requests/phút cho tier free
"""
results = []
rate_limit_delay = 1.0 # 1 giây giữa các request
for i, lead in enumerate(leads_data):
try:
email = self.generate_email(lead, template)
results.append({
"lead_id": lead.get('id'),
"email": email,
"status": "success"
})
# Rate limit protection
if i < len(leads_data) - 1:
time.sleep(rate_limit_delay)
except Exception as e:
results.append({
"lead_id": lead.get('id'),
"status": "failed",
"error": str(e)
})
return results
Demo sử dụng
writer = EmailWriterEngine(api_key="YOUR_HOLYSHEEP_API_KEY")
lead = {
"id": "LEAD-001",
"company_name": "Công ty TNHH Logistics Đông Nam Á",
"industry": "Logistics/Supply Chain",
"employee_count": 300,
"website": "dongnama-logistics.vn",
"pain_point": "quản lý shipment thủ công, mất 4h/ngày",
"competitor": "không",
"score": 85
}
email = writer.generate_email(
lead_info=lead,
template=EmailTemplate.DEMO_INVITATION,
tone="friendly-professional"
)
print(f"Subject: {email['subject']}")
print(f"Latency: {email['latency_ms']}ms")
print(f"Tokens: {email['tokens_used']}")
Kết quả benchmark email generation:
- DeepSeek V3.2 (HolySheep): $0.42/MTok, latency ~180ms
- GPT-4.1 (OpenAI): $8/MTok, latency ~800ms
- Tiết kiệm chi phí: 95%
- Cải thiện tốc độ: 4.4x
Module 3: Integration — Kết nối CRM và Email Service
Để hoàn thiện hệ thống, mình cần kết nối với CRM (Salesforce, HubSpot) và Email service (Gmail, SendGrid). Dưới đây là code integration:
import asyncio
import aiohttp
from typing import List, Dict
from datetime import datetime, timedelta
class SalesAssistantIntegration:
def __init__(self, api_key: str):
self.holysheep_base = "https://api.holysheep.ai/v1"
self.api_key = api_key
# Demo config - thay bằng credentials thực tế
self.crm_config = {
"type": "hubspot", # hoặc 'salesforce', 'pipedrive'
"api_key": "demo_key",
"portal_id": "demo_portal"
}
self.email_config = {
"provider": "sendgrid", # hoặc 'smtp', 'mailgun'
"api_key": "demo_key",
"from_email": "[email protected]",
"from_name": "Sales Team"
}
async def fetch_leads_from_crm(self, days: int = 7) -> List[Dict]:
"""
Lấy leads mới từ CRM trong N ngày gần nhất
"""
# Demo endpoint - thực tế sẽ call HubSpot/Salesforce API
demo_leads = [
{
"id": "CRM-001",
"company_name": "Tech Solutions VN",
"contact_name": "Nguyễn Văn Minh",
"email": "[email protected]",
"industry": "Technology",
"employee_count": 50,
"created_at": datetime.now().isoformat(),
"last_activity": datetime.now().isoformat()
},
{
"id": "CRM-002",
"company_name": "Retail Plus Corp",
"contact_name": "Trần Thị Lan",
"email": "[email protected]",
"industry": "Retail",
"employee_count": 200,
"created_at": (datetime.now() - timedelta(days=2)).isoformat(),
"last_activity": datetime.now().isoformat()
}
]
print(f"📥 Fetched {len(demo_leads)} leads từ CRM")
return demo_leads
async def process_lead_workflow(self, lead: Dict) -> Dict:
"""
Full workflow: Score → Generate Email → Queue for sending
"""
# Step 1: Score lead
score_result = await self._