当前位置: 首页 > Skill >

Whatsapp Context Manager for Agents

Whatsapp Context Manager for Agents

Whatsapp Context Manager for Agents

AI赋能的WhatsApp工具,为客服即时提供客户历史、情绪、优先级、订单详情、VIP检测及回复建议。

0.1.0 2026.11.27 260
获取Skill文件查看使用说明
作 者:顾知 许可证: 更新时间:2026.11.27
本文目录展开

WhatsApp Intelligent Context Manager - Skill Guide

This skill provides an AI-powered context management system for WhatsApp customer service agents, enabling instant access to customer history, sentiment analysis, and smart response suggestions.

Quick Installation

# Download and extract
unzip whatsapp-context-manager.zip
cd whatsapp-context-manager

# Verify installation (no dependencies needed!)
python install_check_whatsapp.py

# Run tests
python test_whatsapp.py

# Try examples
python examples_whatsapp.py

What Problem Does This Solve?

Without This System:

  • ❌ Agents have no context when customer messages arrive
  • ❌ No idea if customer is VIP or first-timer
  • ❌ Can't see order status without switching systems
  • ❌ Don't know if message is urgent or can wait
  • ❌ Guessing what to say instead of smart suggestions

With This System:

  • ✅ Complete customer context in 2 seconds
  • ✅ Automatic sentiment analysis (angry/happy/neutral)
  • ✅ Smart priority (critical/high/normal/low)
  • ✅ Order status right there
  • ✅ AI-powered response suggestions
  • ✅ VIP customer detection

Basic Usage

1. Initialize the System

from whatsapp_context_manager import ContextManager

# Create context manager (creates local database)
manager = ContextManager("production.db")

2. Process Incoming WhatsApp Message

# When a WhatsApp message arrives
context = manager.process_incoming_message(
    phone="+1234567890",
    message_content="Where is my order?!",
    agent_id="agent_001"
)

3. Display Context to Agent

# Show agent what they need to know
print(f"Priority: {context.priority.value}")        # "critical"
print(f"Sentiment: {context.sentiment.value}")      # "negative"
print(f"Category: {context.category}")              # "order_status"
print(f"VIP Customer: {context.customer.is_vip}")   # True/False

# Key insights
for insight in context.key_insights:
    print(f"💡 {insight}")

# Warnings
for warning in context.warnings:
    print(f"⚠️ {warning}")

# Suggested responses
for response in context.suggested_responses:
    print(f"💬 {response}")

4. Send Reply

# Agent sends reply
manager.send_message(
    phone="+1234567890",
    message_content="Your order #12345 is on the way!",
    agent_id="agent_001"
)

What Agent Sees - Dashboard Example

┌──────────────────────────────────────────────────────┐
│                  AGENT DASHBOARD                     │
├──────────────────────────────────────────────────────┤
│ Customer: +1234567890                                │
│ Name: John Doe                                       │
│ VIP: YES                                             │
├──────────────────────────────────────────────────────┤
│ Priority: CRITICAL                                   │
│ Sentiment: NEGATIVE                                  │
│ Category: ORDER_STATUS                               │
├──────────────────────────────────────────────────────┤
│ KEY INSIGHTS:                                        │
│   • 🌟 VIP Customer - Prioritize response            │
│   • 📦 Active Order: #ORD-12345 - shipped            │
│   • 🚚 Tracking: TRK-ABC123                          │
│   • ⚡ Customer expects fast replies (~2min)         │
├──────────────────────────────────────────────────────┤
│ WARNINGS:                                            │
│   • 🚨 CRITICAL: Requires immediate attention!       │
│   • 😡 Customer is very upset - handle with care     │
├──────────────────────────────────────────────────────┤
│ SUGGESTED RESPONSES:                                 │
│   1. Let me check your order status right away.     │
│   2. Your order #ORD-12345 is shipped.               │
└──────────────────────────────────────────────────────┘

Core Features

1. Automatic Sentiment Analysis

Detects customer mood from message:

# System automatically analyzes sentiment
context = manager.process_incoming_message(phone, "This is TERRIBLE!", agent_id)
print(context.sentiment.value)  # "very_negative"

context = manager.process_incoming_message(phone, "Thanks!", agent_id)
print(context.sentiment.value)  # "positive"

Sentiment Levels:

  • 😡 very_negative - Angry, furious, scam
  • 😟 negative - Disappointed, problem
  • 😐 neutral - Questions, info requests
  • 😊 positive - Thanks, happy
  • 🤩 very_positive - Excellent, love it

2. Message Categorization

Automatically categorizes messages:

# System automatically categorizes
context = manager.process_incoming_message(phone, "Where is my package?", agent_id)
print(context.category)  # MessageCategory.ORDER_STATUS

context = manager.process_incoming_message(phone, "Refund please!", agent_id)
print(context.category)  # MessageCategory.PAYMENT

Categories:

  • 📦 ORDER_STATUS - Delivery, tracking, shipment
  • 💳 PAYMENT - Refund, billing, transaction
  • 🔴 COMPLAINT - Problem, issue, broken
  • 🛍️ PRODUCT_INQUIRY - Price, stock, features
  • 🆘 SUPPORT - Help, how-to, questions
  • 💰 SALES - Buy, purchase, interested
  • ⭐ FEEDBACK - Review, opinion
  • ❓ OTHER - Uncategorized

3. Priority Calculation

Smart priority based on multiple factors:

# System calculates priority
context = manager.process_incoming_message(
    phone="+1234567890",
    message_content="My payment failed!!!",
    agent_id="agent_001"
)
print(context.priority.value)  # "critical"

Priority Levels:

  • 🔴 CRITICAL - Angry customer, payment issue, VIP unhappy
  • 🟠 HIGH - Complaints, negative sentiment
  • 🟡 NORMAL - General questions
  • 🟢 LOW - Info requests, positive feedback

4. Response Suggestions

AI suggests appropriate responses:

context = manager.process_incoming_message(
    phone="+1234567890",
    message_content="When will my order arrive?",
    agent_id="agent_001"
)

# Get suggestions
for response in context.suggested_responses:
    print(response)
# Output:
# "Let me check your order status right away."
# "Your order #12345 is currently shipped."
# "Expected delivery is tomorrow."

Advanced Features

Order Integration

Add and track customer orders:

from whatsapp_context_manager import Order
from datetime import datetime, timedelta

# Add order to system
order = Order(
    order_id="ORD-12345",
    customer_id=context.customer.customer_id,
    status="shipped",
    amount=99.99,
    items=[
        {"name": "Wireless Headphones", "quantity": 1, "price": 99.99}
    ],
    created_at=datetime.now().isoformat(),
    updated_at=datetime.now().isoformat(),
    tracking_number="TRK-ABC123",
    estimated_delivery=(datetime.now() + timedelta(days=2)).strftime("%Y-%m-%d")
)

manager.add_order(order)

# Now when customer asks about order, agent sees all details
context = manager.process_incoming_message(phone, "Order status?", agent_id)
print(context.active_orders[0].tracking_number)  # "TRK-ABC123"

VIP Customer Management

Mark and manage VIP customers:

# Update customer to VIP
manager.update_customer_info(
    phone="+1234567890",
    name="John Doe",
    email="john@example.com",
    is_vip=True,
    tags=["premium", "loyal", "high-value"],
    notes="Always responds best to quick, direct answers"
)

# Future messages automatically show VIP status
context = manager.process_incoming_message(phone, "Hello", agent_id)
print(context.customer.is_vip)  # True
print(context.customer.tags)    # ["premium", "loyal", "high-value"]

Conversation History

Access complete conversation history:

# Get context (includes recent messages)
context = manager.process_incoming_message(phone, "Need help", agent_id)

# View recent messages
for msg in context.recent_messages:
    direction = "Customer" if msg.direction == "inbound" else "Agent"
    print(f"{direction}: {msg.content}")

Customer Profile

Access complete customer profile:

context = manager.process_incoming_message(phone, "Hello", agent_id)

customer = context.customer
print(f"Phone: {customer.phone}")
print(f"Name: {customer.name}")
print(f"Total Messages: {customer.total_messages}")
print(f"VIP: {customer.is_vip}")
print(f"Tags: {customer.tags}")
print(f"Notes: {customer.notes}")
print(f"Last Contact: {customer.last_contact}")
print(f"Sentiment History: {customer.sentiment_history}")

Common Use Cases

Use Case 1: Order Status Inquiry

# Customer: "Where is my order?"
context = manager.process_incoming_message(
    phone="+1234567890",
    message_content="Where is my order?",
    agent_id="agent_001"
)

# Agent sees:
if context.active_orders:
    order = context.active_orders[0]
    print(f"Order ID: {order.order_id}")
    print(f"Status: {order.status}")
    print(f"Tracking: {order.tracking_number}")
    print(f"Est. Delivery: {order.estimated_delivery}")

# Suggested response
print(context.suggested_responses[0])
# "Your order #ORD-12345 is shipped. Tracking: TRK-ABC123"

Use Case 2: Angry Customer

# Customer: "This is TERRIBLE! I want a refund NOW!!!"
context = manager.process_incoming_message(
    phone="+1234567890",
    message_content="This is TERRIBLE! I want a refund NOW!!!",
    agent_id="agent_001"
)

# System detects:
print(context.priority.value)   # "critical"
print(context.sentiment.value)  # "very_negative"

# Agent sees warnings:
for warning in context.warnings:
    print(warning)
# "🚨 CRITICAL: Requires immediate attention!"
# "😡 Customer is very upset - handle with care"

# Suggested response
print(context.suggested_responses[0])
# "I sincerely apologize for the inconvenience. Let me help resolve this."

Use Case 3: Multiple Customers Priority Queue

# Process messages from multiple customers
customers = [
    ("+1111111111", "Can I get some info?"),
    ("+2222222222", "My payment failed!!!"),
    ("+3333333333", "I have a complaint"),
    ("+4444444444", "Thanks for the help!"),
]

contexts = []
for phone, message in customers:
    context = manager.process_incoming_message(phone, message, "agent_001")
    contexts.append((phone, context))

# Sort by priority
priority_order = {
    MessagePriority.CRITICAL: 0,
    MessagePriority.HIGH: 1,
    MessagePriority.NORMAL: 2,
    MessagePriority.LOW: 3
}
contexts.sort(key=lambda x: priority_order[x[1].priority])

# Agent dashboard shows:
# 1. 🔴 +2222222222 - CRITICAL - Payment failed
# 2. 🟠 +3333333333 - HIGH - Complaint
# 3. 🟡 +1111111111 - NORMAL - Info request
# 4. 🟢 +4444444444 - LOW - Thank you message

Use Case 4: First-time vs Returning Customer

# System automatically tracks
context = manager.process_incoming_message(
    phone="+9999999999",  # New number
    message_content="Hello",
    agent_id="agent_001"
)

# Check if first time
if context.customer.total_messages == 1:
    print("👋 First time customer!")
    # Show introduction, onboarding info
else:
    print(f"📊 Returning customer ({context.customer.total_messages} messages)")
    # Show history, previous orders

Integration Examples

With WhatsApp Business API

from whatsapp_business_api import WhatsAppClient
from whatsapp_context_manager import ContextManager

# Initialize
wa_client = WhatsAppClient(api_key="your_key")
manager = ContextManager("production.db")

# Handle incoming messages
@wa_client.on_message
def handle_message(phone, message):
    # Get context
    context = manager.process_incoming_message(
        phone=phone,
        message_content=message,
        agent_id="auto_agent"
    )
    
    # Display to agent dashboard
    display_to_agent(context)
    
    # If critical, alert supervisor
    if context.priority == MessagePriority.CRITICAL:
        notify_supervisor(context)

With Web Dashboard

from flask import Flask, jsonify
from whatsapp_context_manager import ContextManager

app = Flask(__name__)
manager = ContextManager()

@app.route('/api/message', methods=['POST'])
def process_message():
    data = request.json
    
    # Process message
    context = manager.process_incoming_message(
        phone=data['phone'],
        message_content=data['message'],
        agent_id=data['agent_id']
    )
    
    # Return context as JSON
    return jsonify(context.to_dict())

Best Practices

1. Always Process Through System

# Good ✅
context = manager.process_incoming_message(phone, message, agent_id)
# Agent has full context

# Bad ❌
# Responding without context
send_reply_directly(phone, "Hello")  # Agent is blind

2. Mark VIP Customers

# Identify high-value customers early
if customer_is_high_value(phone):
    manager.update_customer_info(
        phone=phone,
        is_vip=True,
        tags=["high-value", "premium"]
    )

3. Track Orders

# Add orders to system for automatic context
when_order_placed():
    manager.add_order(order)
    
# Now agents automatically see order status when customer asks

4. Use Suggested Responses

# Get AI suggestions
context = manager.process_incoming_message(phone, message, agent_id)

# Show to agent for quick selection
for i, response in enumerate(context.suggested_responses, 1):
    print(f"{i}. {response}")

5. Monitor Priority Queue

# Get all pending messages
pending_contexts = get_all_pending_messages()

# Sort by priority
pending_contexts.sort(key=lambda x: priority_order[x.priority])

# Agents work from top (critical) to bottom (low)

Performance Tips

1. Database Management

# Use separate databases for different purposes
dev_manager = ContextManager("development.db")
prod_manager = ContextManager("production.db")
test_manager = ContextManager("test.db")

2. Batch Processing

# Process multiple messages efficiently
for phone, message in message_queue:
    context = manager.process_incoming_message(phone, message, agent_id)
    process_context(context)

3. Regular Cleanup

# Archive old conversations (optional)
# System stores everything by default
# Implement custom archival if needed

Security Features

  • Local Storage: All data stored locally in SQLite
  • No External Dependencies: Pure Python, no third-party libraries
  • Data Integrity: SHA-256 checksums
  • Secure Queries: Parameterized SQL, no injection risks
  • Privacy: No data sent to external services

Troubleshooting

Issue: Database locked

# Use different database per process
manager1 = ContextManager("agent1.db")
manager2 = ContextManager("agent2.db")

Issue: Old data in tests

# Clean up test databases
import os
if os.path.exists("test.db"):
    os.remove("test.db")

Issue: No order suggestions

# Make sure orders are added to system
order = Order(...)
manager.add_order(order)

File Structure

whatsapp-context-manager/
├── whatsapp_context_manager.py  # Main library
├── examples_whatsapp.py         # 8 usage examples
├── test_whatsapp.py             # Complete test suite
├── README_WHATSAPP.md           # Full documentation
├── install_check_whatsapp.py    # Installation check
├── requirements_whatsapp.txt    # Dependencies (none!)
├── LICENSE_WHATSAPP             # MIT License
└── .gitignore_whatsapp          # Git ignore rules

Requirements

  • Python 3.8 or higher
  • No external dependencies!

Testing

# Run all tests
python test_whatsapp.py

# Should show:
# ✅ Sentiment analysis tests passed
# ✅ Message categorization tests passed
# ✅ Priority calculation tests passed
# ✅ Customer management tests passed
# ✅ Message storage tests passed
# ✅ Order management tests passed
# ✅ VIP customer tests passed
# ✅ Sentiment tracking tests passed
# ✅ Response suggestions tests passed
# ✅ Priority queue tests passed
# ✅ Conversation flow tests passed
# ✅ Context export tests passed
# ✅ ALL TESTS PASSED

Examples

Run the examples to see the system in action:

python examples_whatsapp.py

Includes:

  1. Basic message processing
  2. Customer with active order
  3. Angry customer scenario
  4. VIP customer handling
  5. Conversation history
  6. Multiple customers priority queue
  7. Agent dashboard view
  8. Context export to JSON

Getting Help

  • 📖 Read full documentation: README_WHATSAPP.md
  • 💻 Check examples: examples_whatsapp.py
  • 🧪 Run tests: test_whatsapp.py
  • 🐛 Report issues on GitHub
  • ⭐ Star the repo if helpful!

Next Steps

  1. ✅ Install and verify: python install_check_whatsapp.py
  2. ✅ Run tests: python test_whatsapp.py
  3. ✅ Try examples: python examples_whatsapp.py
  4. ✅ Integrate with your WhatsApp system
  5. ✅ Customize for your needs

License

MIT License - see LICENSE_WHATSAPP file

Author

cerbug45

  • GitHub: @cerbug45

Transform your WhatsApp customer service from reactive to proactive! 🚀

推荐文章

更多
PHP时间戳与日期字符串相互转换方法详解

本文介绍PHP中时间数值(Unix时间戳)与日期字符串之间的相互转换方法。通过strtotime和date函数,实现将当前时间、指定日期转换为时间戳,以及将时间戳格式化为可读的日期时间字符串,并提供相关在线计算工具推荐。

2025.11.30 1,034
PHP日期转时间戳时区偏差怎么解决

在 PHP 中将日期字符串转换为时间戳时,若未显式指定时区,默认使用脚本配置的 date.timezone 或系统时区。当服务器时区与业务逻辑预期(如 UTC )不一致时,会产生偏差。解决核心是确保输入字符串携带明确时区信息,或在转换前统一设置时区上下文。

2026.10.24 1,031
PHP跨域配置:怎么安全地允许指定域名而非使用通配符

在 PHP 中安全地允许指定域名跨域,核心是解析请求头中的 Origin ,验证其是否在白名单内,然后动态设置 Access-Control-Allow-Origin 响应头。不要使用通配符 * ,也不要硬编码单一域名。

2025.03.29 1,018
JavaScript中利用replace结合正则实现replaceAll效果

JavaScript原生仅支持replace()进行单次或全局替换,缺乏类似Java的replaceAll()便捷方法。本文总结四种在JS中实现全量替换的方案:使用带g标志的正则、带gm标志的正则、扩展String原型以及split后join。通过对比代码示例,展示各方法的实现细节与适用场景,帮助开发者根据需求选择最优解。

2025.04.29 1,017
OpenAI的Jalapeno芯片未落地,教你分辨300兆瓦算力消息

OpenAI计划在SB Energy租赁的数据中心部署约300兆瓦自研Jalapeno推理芯片,但目前双方仍处于洽谈阶段,交易细节与上线时间表均未公布。本文带你按报道原文核实项目所处阶段,厘清芯片发布、电力功率与实际推理算力的边界,并将融资意向与签约、开工、投运节点分开追踪,避免误将规划容量计入现有算力。

2026.12.02 1,013
PHP实现基础文件上传:HTML表单与$_FILES处理流程

在 HTML 表单中设置 enctype="multipart/form-data" ,并在 PHP 后端通过 $_FILES 数组接收文件,调用 move_uploaded_file() 将临时文件移动到目标目录即可完成上传。

2026.09.07 1,013
Skill 文件
  • SKILL.md
    • WhatsApp Intelligent Context Manager - Skill Guide
    • Quick Installation
    • What Problem Does This Solve?
    • Basic Usage
      • 1. Initialize the System
      • 2. Process Incoming WhatsApp Message
      • 3. Display Context to Agent
      • 4. Send Reply
    • What Agent Sees - Dashboard Example
    • Core Features
      • 1. Automatic Sentiment Analysis
      • 2. Message Categorization
      • 3. Priority Calculation
      • 4. Response Suggestions
    • Advanced Features
      • Order Integration
      • VIP Customer Management
      • Conversation History
      • Customer Profile
    • Common Use Cases
      • Use Case 1: Order Status Inquiry
      • Use Case 2: Angry Customer
      • Use Case 3: Multiple Customers Priority Queue
      • Use Case 4: First-time vs Returning Customer
    • Integration Examples
      • With WhatsApp Business API
      • With Web Dashboard
    • Best Practices
      • 1. Always Process Through System
      • 2. Mark VIP Customers
      • 3. Track Orders
      • 4. Use Suggested Responses
      • 5. Monitor Priority Queue
    • Performance Tips
      • 1. Database Management
      • 2. Batch Processing
      • 3. Regular Cleanup
    • Security Features
    • Troubleshooting
      • Issue: Database locked
      • Issue: Old data in tests
      • Issue: No order suggestions
    • File Structure
    • Requirements
    • Testing
    • Examples
    • Getting Help
    • Next Steps
    • License
    • Author
  • 项目或源文件

相关 Skill

更多
Context Manager Context Manager 【使用场景】当用户需管理个人上下文;提及「管理上下文」「整理信息」「记录认知」;检测到「决策背景」「记忆外脑」「认知地图」等关键词。【定位】面向AI时代的个人上下文管理需求,打造思维树构建师能力。
service-qa-coach service-qa-coach Review support quality for chat, email, phone, social DM, or marketplace service teams. Use when a team needs a QA scorecard, failure-mode analysis, coaching plan, calibration checklist, or service-improvement brief without live ticketing, CRM, or contact-center system access.
高中数学作业批改助手 高中数学作业批改助手 >图片识别 直接读取学生手写作答照片,识别公式、符号、步骤 🧮 自动推导 根据题目自动生成参考答案和评分细则,无需教师预设 📊 逐步给分 每个关键步骤独立评分,体现过程分 📝 结构化报告 输出含识别内容、参考答案、逐步评分、改进建议的完整报告 🗂 批量批改 支持一次性批改多道题,最终汇总得分表
Vibration Analysis Vibration Analysis 分析来自CMS趋势、RMS/峰值、频谱及SCADA报警的风机传动链(主轴、齿轮箱、发电机)振动数据。
Traditional Bone Tool Making Basics Traditional Bone Tool Making Basics Use when you need custom, durable, repairable tools like awls, needles, scrapers, harpoons, or fishing hooks made from local animal bones or antlers and comm...