mirror of
https://github.com/langbot-app/LangBot.git
synced 2026-11-25 01:52:07 +08:00
feat(plugins): add LeadCapture (purchase intent → contact → Resend email) (#2919)
New misc plugin langbot-team/LeadCapture 0.1.0 (购买意向留资): - after each AI reply (NormalMessageResponded) a configured LLM judges strong purchase intent against a configurable prompt over the recent conversation (monitoring.messages, read-only) - on strong intent, a fixed contact-request text is appended to that reply, once per bot+user - user messages are then checked for contact details (patterns for CN mobile/landline, email, WeChat; LLM extraction as fallback) - on capture, the full conversation is emailed via Resend (configurable API key, sender, recipients) with a .txt transcript attachment; failed sends are retried on later replies, up to 3 attempts; an optional thank-you is appended to the next reply - every failure is logged and never breaks the conversation Misc plugin CI now uses any plugin's own requirements-dev.txt. Co-authored-by: Claude Opus 5.5 <[email protected]> Co-authored-by: multica-agent <[email protected]>
This commit is contained in:
co-authored by
Claude Opus 5.5
multica-agent
parent
5dbc2eda79
commit
670ec4f59b
@@ -55,6 +55,7 @@ publication. Plugins are not included in Core release artifacts.
|
||||
- [HelloPlugin](misc/HelloPlugin/README.md)
|
||||
- [HumanTakeover](misc/HumanTakeover/README.md)
|
||||
- [KeywordAlert](misc/KeywordAlert/README.md)
|
||||
- [LeadCapture](misc/LeadCapture/README.md)
|
||||
- [MCBotPlugin](misc/MCBotPlugin/README.md)
|
||||
- [PowerContext](misc/PowerContext/README.md)
|
||||
- [QWeather](misc/QWeather/README.md)
|
||||
|
||||
@@ -230,6 +230,13 @@
|
||||
"path": "misc/KeywordAlert",
|
||||
"repository": "https://github.com/langbot-app/LangBot/tree/master/plugins/misc/KeywordAlert"
|
||||
},
|
||||
{
|
||||
"id": "langbot-team/LeadCapture",
|
||||
"version": "0.1.0",
|
||||
"category": "misc",
|
||||
"path": "misc/LeadCapture",
|
||||
"repository": "https://github.com/langbot-app/LangBot/tree/master/plugins/misc/LeadCapture"
|
||||
},
|
||||
{
|
||||
"id": "RockChinQ/MCBotPlugin",
|
||||
"version": "0.1.3",
|
||||
|
||||
@@ -0,0 +1,4 @@
|
||||
__pycache__/
|
||||
.pytest_cache/
|
||||
dist/
|
||||
.venv/
|
||||
@@ -0,0 +1,100 @@
|
||||
# Purchase Intent Lead Capture
|
||||
|
||||
Let your AI customer service notice customers who want to buy. After every AI reply, the plugin reads the conversation with a model you choose and against criteria you write, and decides whether the customer has **strong purchase intent**. If so, it appends a contact request to that reply, only once per customer. When the customer leaves a phone number, WeChat ID or email, the plugin sends the **contact details plus the entire conversation with that customer** to your inbox through [Resend](https://resend.com).
|
||||
|
||||
Works for private chats on any platform (WeChat Official Account, WeCom customer service, Telegram, QQ, …).
|
||||
|
||||
## What it looks like
|
||||
|
||||
1. A customer chats with the AI, e.g. "How much is the annual plan? Can you issue an invoice?"
|
||||
2. After the AI replies, the plugin judges strong intent and appends: "为了更好地为您服务,方便留下您的手机号或微信号吗?我们的顾问会尽快与您联系。" (May we have your phone or WeChat so an advisor can contact you?)
|
||||
3. The customer replies "138 0013 8000". The plugin recognizes the contact and immediately sends an email:
|
||||
- subject: `【购买意向】138 0013 8000 · <bot name>`;
|
||||
- body: contact, user ID, source bot, the reason for the intent judgment, capture time, first contact time, message count and the full conversation;
|
||||
- attachment: `conversation-<time>.txt` with the full transcript.
|
||||
4. The next AI reply ends with a thank-you: "已收到您的联系方式,我们的顾问会尽快与您联系,感谢您的信任!"
|
||||
5. That customer is never judged or asked again. A customer who does not leave contact details is not asked a second time either.
|
||||
|
||||
## Setup
|
||||
|
||||
### Step 1: Prepare Resend
|
||||
|
||||
1. Sign up at [resend.com](https://resend.com).
|
||||
2. **Domains → Add Domain**: add your sending domain (e.g. `example.com`), add the DNS records it shows, and wait for **Verified**.
|
||||
3. **API Keys → Create API Key** with **Sending access**, and copy the `re_…` key (it is shown once).
|
||||
|
||||
> Without a verified domain, Resend only lets `[email protected]` send to your own Resend account address, which is useful only for testing.
|
||||
|
||||
### Step 2: Install the plugin and confirm permissions
|
||||
|
||||
| Permission | Used for |
|
||||
| --- | --- |
|
||||
| `models.invoke` | Judging intent and reading contact details |
|
||||
| `storage.plugin` | Remembering each customer's asked / captured state |
|
||||
| `monitoring.messages` (read-only message history) | Reading the conversation for judging and for the email |
|
||||
|
||||
### Step 3: Fill in the plugin configuration
|
||||
|
||||
| Setting | What to enter |
|
||||
| --- | --- |
|
||||
| Model for judging intent | A chat model. It is called once after every AI reply, so a fast, inexpensive model is best |
|
||||
| Intent criteria (prompt) | In plain language, what counts as strong purchase intent for your business, e.g. asking about price, plans, contracts, invoices, trials or go-live dates counts; asking about features or small talk does not. A general default is provided |
|
||||
| Messages used for judging | How many recent messages to read, default 20, max 100 |
|
||||
| Contact request text | Fixed text appended to the AI reply when strong intent is detected |
|
||||
| Thank-you text | Appended to the next AI reply after contact details arrive; leave empty to disable |
|
||||
| Resend API key | The `re_…` key from step 1 |
|
||||
| Sender address | An address on your verified domain, e.g. `[email protected]` or `Leads <[email protected]>` |
|
||||
| Recipient addresses | One or more inboxes that receive leads |
|
||||
|
||||
### Step 4: Enable it in the Pipeline
|
||||
|
||||
The plugin works inside a Pipeline. Make sure the customer-facing bot routes messages to a **Pipeline** that can use this plugin.
|
||||
|
||||
### Step 5: Test it
|
||||
|
||||
Chat with the bot from your own account and ask about buying (price, contract, trial). Check that the AI reply ends with the contact request, reply with a phone number and check the inbox.
|
||||
|
||||
## How contact details are recognized
|
||||
|
||||
- Patterns first: mainland China mobile numbers (with optional `+86`, spaces or dashes), landlines with an area code (e.g. `010-12345678`), email addresses, and WeChat IDs after "微信 / vx / wx".
|
||||
- If no pattern matches, the model extracts it from that message (e.g. "add my QQ 123456789"). It is told never to invent one and to return empty when there is none.
|
||||
- Every customer message is checked until contact details are found, and none after that.
|
||||
|
||||
## Troubleshooting
|
||||
|
||||
**No email arrives.** Look for `LeadCapture email failed (...)` in the plugin log:
|
||||
- `not_configured`: the API key, sender or recipients are missing.
|
||||
- `http_403:validation_error`: the sending domain is not verified in Resend, or the sender is not on it.
|
||||
- `http_401` / `http_403`: wrong API key or insufficient permission.
|
||||
- `network:...`: the server cannot reach `api.resend.com`.
|
||||
|
||||
A failed email is retried on later AI replies, **up to 3 attempts in total**.
|
||||
|
||||
**The contact request never appears.** Check that a model is selected and that the criteria are specific enough, and look for `intent evaluation failed` in the log. A customer who was already asked is not asked again.
|
||||
|
||||
**AI replies got slower.** Each AI reply triggers one extra model call (usually 1–3 s). Use a faster model or fewer messages. In WeChat Official Account auto mode replies are pushed asynchronously anyway, so the impact is small.
|
||||
|
||||
**Images in the AI reply.** When text is appended, that reply is sent as text; images in it become placeholders.
|
||||
|
||||
## Limits
|
||||
|
||||
- Private chats only.
|
||||
- Each customer is asked once; state is kept per bot + user. Reinstalling the plugin clears the state of all customers.
|
||||
- Emails contain customers' contact details and full conversations; make sure that fits your privacy and data policy.
|
||||
- Transcripts come from LangBot's message records, up to 5,000 messages.
|
||||
|
||||
## For developers
|
||||
|
||||
One EventListener (`components/event_listener/lead.py`):
|
||||
|
||||
- `NormalMessageResponded` judges intent and appends the request or thank-you through `reply_message_chain`.
|
||||
- `PersonMessageReceived` looks for contact details while the customer is in the asked state, and sends the email through Resend.
|
||||
|
||||
Conversations come from the read-only `monitoring.messages` Workspace operation. Every failure is only logged and never breaks the conversation.
|
||||
|
||||
```bash
|
||||
uv venv
|
||||
uv pip install -r requirements-dev.txt
|
||||
uv run pytest -q
|
||||
uv run ruff check .
|
||||
```
|
||||
@@ -0,0 +1,5 @@
|
||||
# Shared runtime
|
||||
|
||||
LeadCapture declares `shared-runtime-v1` and `stateless-v1`. The EventListener keeps no invocation data; it reads configuration and the installation binding only inside event invocations.
|
||||
|
||||
State rows are keyed by `instance_uuid:workspace_uuid:installation_uuid`, bot UUID and user ID, one row per customer (`asked` or `captured`, plus email delivery status). A shared worker without a binding refuses storage access; dedicated placement uses a dedicated scope. One process-local lock per installation serializes judging, contact capture and email delivery so a customer is asked at most once. Revocation removes only the affected lock. No background tasks are created: judging runs inside `NormalMessageResponded`, capture and email inside `PersonMessageReceived`, and failed emails are retried only on later events of the same customer.
|
||||
@@ -0,0 +1 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64"><rect width="64" height="64" rx="14" fill="#0E9F6E"/><path d="M14 22h36v22a4 4 0 0 1-4 4H18a4 4 0 0 1-4-4z" fill="#fff"/><path d="M14 22l18 13 18-13" fill="none" stroke="#0E9F6E" stroke-width="3" stroke-linejoin="round"/><circle cx="47" cy="17" r="8" fill="#FBBF24"/><path d="M47 13v8M43 17h8" stroke="#fff" stroke-width="2.5" stroke-linecap="round"/></svg>
|
||||
|
After Width: | Height: | Size: 418 B |
@@ -0,0 +1,32 @@
|
||||
import logging
|
||||
|
||||
from langbot_plugin.api.definition.components.common.event_listener import EventListener
|
||||
from langbot_plugin.api.entities import events
|
||||
|
||||
from main import permission_denied
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
class LeadListener(EventListener):
|
||||
async def initialize(self):
|
||||
await super().initialize()
|
||||
|
||||
@self.handler(events.PersonMessageReceived)
|
||||
async def on_person(event_context):
|
||||
await self.guard(self.plugin.on_person_message(event_context))
|
||||
|
||||
@self.handler(events.NormalMessageResponded)
|
||||
async def on_responded(event_context):
|
||||
await self.guard(self.plugin.on_responded(event_context))
|
||||
|
||||
@staticmethod
|
||||
async def guard(call):
|
||||
"""Never let lead capture break the conversation."""
|
||||
try:
|
||||
await call
|
||||
except Exception as error:
|
||||
if permission_denied(error):
|
||||
logger.warning("LeadCapture is missing a permission; confirm it on the plugin page.")
|
||||
return
|
||||
logger.exception("LeadCapture failed")
|
||||
@@ -0,0 +1,27 @@
|
||||
apiVersion: v1
|
||||
kind: EventListener
|
||||
metadata:
|
||||
name: lead
|
||||
label:
|
||||
en_US: Purchase intent lead capture
|
||||
zh_Hans: 购买意向留资
|
||||
zh_Hant: 購買意向留資
|
||||
ja_JP: 購入意向リード獲得
|
||||
es_ES: Captación de clientes con intención de compra
|
||||
ru_RU: Сбор контактов при намерении купить
|
||||
th_TH: เก็บข้อมูลลูกค้าที่ตั้งใจซื้อ
|
||||
vi_VN: Thu thập khách hàng có ý định mua
|
||||
description:
|
||||
en_US: Judge purchase intent after AI replies, ask once for contact details, and email the lead.
|
||||
zh_Hans: 在 AI 回复后判断购买意愿,只请求一次联系方式,并把线索发到邮箱。
|
||||
zh_Hant: 在 AI 回覆後判斷購買意願,只請求一次聯絡方式,並將線索寄到信箱。
|
||||
ja_JP: AI の返信後に購入意向を判定し、連絡先を一度だけ尋ね、リードをメールで送ります。
|
||||
es_ES: Evalúa la intención de compra tras la respuesta de la IA, pide el contacto una vez y envía el cliente por correo.
|
||||
ru_RU: Оценивает намерение купить после ответа ИИ, однажды просит контакты и отправляет лид на почту.
|
||||
th_TH: ประเมินความตั้งใจซื้อหลัง AI ตอบ ขอช่องทางติดต่อหนึ่งครั้ง และส่งข้อมูลทางอีเมล
|
||||
vi_VN: Đánh giá ý định mua sau khi AI trả lời, hỏi liên hệ một lần và gửi khách hàng tiềm năng qua email.
|
||||
spec: {}
|
||||
execution:
|
||||
python:
|
||||
path: lead.py
|
||||
attr: LeadListener
|
||||
@@ -0,0 +1,387 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import base64
|
||||
import html
|
||||
import json
|
||||
import logging
|
||||
import os
|
||||
import re
|
||||
import time
|
||||
from datetime import UTC, datetime
|
||||
from urllib.parse import quote
|
||||
|
||||
import httpx
|
||||
|
||||
from langbot_plugin.api.definition.plugin import BasePlugin
|
||||
from langbot_plugin.api.entities.builtin.platform import message
|
||||
from langbot_plugin.api.entities.builtin.provider.message import ContentElement, Message
|
||||
from langbot_plugin.api.proxies.runner import PermissionDeniedError
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
RESEND_URL = "https://api.resend.com/emails"
|
||||
DEFAULT_INTENT_PROMPT = (
|
||||
"用户明确表达了购买、下单、试用、报价、签约、采购或与销售沟通的意愿,"
|
||||
"或在询问价格、套餐、付款方式、发票、合同、交付时间等成交相关细节,视为强烈购买意愿。"
|
||||
"只是了解产品功能、闲聊或技术咨询,不算强烈购买意愿。"
|
||||
)
|
||||
DEFAULT_ASK_TEXT = "为了更好地为您服务,方便留下您的手机号或微信号吗?我们的顾问会尽快与您联系。"
|
||||
DEFAULT_THANKS_TEXT = "已收到您的联系方式,我们的顾问会尽快与您联系,感谢您的信任!"
|
||||
MAX_EMAIL_ATTEMPTS = 3
|
||||
PAGE_SIZE = 100
|
||||
MAX_TRANSCRIPT_MESSAGES = 5000
|
||||
COMPONENT_LABELS = {
|
||||
"Image": "[图片]", "Voice": "[语音]", "File": "[文件]", "Face": "[表情]", "Forward": "[转发]",
|
||||
}
|
||||
|
||||
EMAIL_RE = re.compile(r"[A-Za-z0-9._%+-]+@[A-Za-z0-9-]+(?:\.[A-Za-z0-9-]+)*\.[A-Za-z]{2,}")
|
||||
MOBILE_RE = re.compile(r"(?<!\d)(?:\+?86[-\s]?)?1[3-9]\d(?:[-\s]?\d{4}){2}(?!\d)")
|
||||
LANDLINE_RE = re.compile(r"(?<!\d)0\d{2,3}-\d{7,8}(?!\d)")
|
||||
WECHAT_RE = re.compile(
|
||||
r"(?:微信号?|weixin|wechat|vx|wx|v信|威信)\s*(?:号|id)?\s*[::是为]?\s*([A-Za-z][-_A-Za-z0-9]{5,19})",
|
||||
re.IGNORECASE,
|
||||
)
|
||||
|
||||
|
||||
def permission_denied(error: Exception) -> bool:
|
||||
return (
|
||||
isinstance(error, PermissionDeniedError)
|
||||
or getattr(getattr(error, "error", error), "code", None) == "permission_denied"
|
||||
or "permission_denied" in str(error)
|
||||
)
|
||||
|
||||
|
||||
def plain_text(chain) -> str:
|
||||
return "".join(part.text for part in chain if isinstance(part, message.Plain)).strip()
|
||||
|
||||
|
||||
def find_contact(text: str) -> str:
|
||||
"""Return contact details found by pattern, or an empty string."""
|
||||
found = []
|
||||
for pattern in (MOBILE_RE, LANDLINE_RE, EMAIL_RE):
|
||||
found.extend(match.group(0).strip() for match in pattern.finditer(text))
|
||||
found.extend(f"微信: {match.group(1)}" for match in WECHAT_RE.finditer(text))
|
||||
unique = list(dict.fromkeys(found))
|
||||
return ";".join(unique)
|
||||
|
||||
|
||||
def stored_text(content) -> str:
|
||||
"""Render a monitoring message_content (JSON message chain) as plain text."""
|
||||
try:
|
||||
parts = json.loads(content) if isinstance(content, str) else content
|
||||
except ValueError:
|
||||
return str(content)
|
||||
if not isinstance(parts, list):
|
||||
return str(parts)
|
||||
rendered = []
|
||||
for part in parts:
|
||||
if not isinstance(part, dict) or part.get("type") in ("Source", "Quote", "At"):
|
||||
continue
|
||||
if part.get("type") == "Plain":
|
||||
rendered.append(str(part.get("text", "")))
|
||||
else:
|
||||
rendered.append(COMPONENT_LABELS.get(part.get("type"), f"[{part.get('type')}]"))
|
||||
return "".join(rendered).strip()
|
||||
|
||||
|
||||
def utc_label(timestamp, seconds: bool = True) -> str:
|
||||
try:
|
||||
moment = datetime.fromisoformat(str(timestamp))
|
||||
except ValueError:
|
||||
return str(timestamp)
|
||||
if moment.tzinfo is None:
|
||||
moment = moment.replace(tzinfo=UTC)
|
||||
return moment.astimezone(UTC).strftime("%Y-%m-%d %H:%M:%S" if seconds else "%Y-%m-%d %H:%M")
|
||||
|
||||
|
||||
def parse_json_object(text: str) -> dict:
|
||||
"""Extract the first JSON object from an LLM response (tolerates code fences and prose)."""
|
||||
match = re.search(r"\{.*\}", text or "", re.S)
|
||||
if not match:
|
||||
return {}
|
||||
try:
|
||||
value = json.loads(match.group(0))
|
||||
except ValueError:
|
||||
return {}
|
||||
return value if isinstance(value, dict) else {}
|
||||
|
||||
|
||||
def response_text(response) -> str:
|
||||
content = getattr(response, "content", "")
|
||||
if isinstance(content, str):
|
||||
return content.strip()
|
||||
if isinstance(content, list):
|
||||
return "\n".join(getattr(part, "text", "") or "" for part in content).strip()
|
||||
return ""
|
||||
|
||||
|
||||
def role_label(role: str) -> str:
|
||||
return "用户" if role == "user" else "AI"
|
||||
|
||||
|
||||
class LeadCapture(BasePlugin):
|
||||
"""Detect strong purchase intent with an LLM, ask once for contact details, email the lead."""
|
||||
|
||||
def __init__(self):
|
||||
super().__init__()
|
||||
self._locks: dict[str, asyncio.Lock] = {}
|
||||
|
||||
def scope(self, binding=None) -> str:
|
||||
if binding is None:
|
||||
binding = self.get_installation_binding()
|
||||
if binding is not None:
|
||||
return f"{binding.instance_uuid}:{binding.workspace_uuid}:{binding.installation_uuid}"
|
||||
if os.environ.get("LANGBOT_PLUGIN_RUNTIME_PROFILE") == "shared":
|
||||
raise RuntimeError("LeadCapture requires an installation binding in shared runtime")
|
||||
return "dedicated"
|
||||
|
||||
async def on_installation_revoked(self, binding):
|
||||
self._locks.pop(self.scope(binding), None)
|
||||
|
||||
async def destroy(self):
|
||||
self._locks.clear()
|
||||
|
||||
def lock(self) -> asyncio.Lock:
|
||||
return self._locks.setdefault(self.scope(), asyncio.Lock())
|
||||
|
||||
def key(self, bot: str, user: str) -> str:
|
||||
return "lead:" + ":".join(quote(str(part), safe="") for part in (self.scope(), bot, user))
|
||||
|
||||
async def load(self, key: str):
|
||||
if key not in await self.get_plugin_storage_keys():
|
||||
return None
|
||||
return json.loads(await self.get_plugin_storage(key))
|
||||
|
||||
async def save(self, key: str, value):
|
||||
await self.set_plugin_storage(key, json.dumps(value, ensure_ascii=False).encode("utf-8"))
|
||||
|
||||
# ---- conversation history --------------------------------------------------
|
||||
|
||||
async def messages_page(self, bot: str, user: str, limit: int, offset: int = 0):
|
||||
"""Return (rows newest first, total) for the user's private session."""
|
||||
response = await self.workspace.monitoring.messages(
|
||||
bot_ids=[bot], session_ids=[f"person_{user}"], limit=limit, offset=offset,
|
||||
)
|
||||
if not isinstance(response, dict) or not response.get("ok"):
|
||||
error = (response or {}).get("error", {}) if isinstance(response, dict) else {}
|
||||
raise RuntimeError(f"monitoring.messages failed: {error.get('code', 'error')}")
|
||||
rows, total = (list(response.get("result") or []) + [[], 0])[:2]
|
||||
return (rows if isinstance(rows, list) else []), int(total or 0)
|
||||
|
||||
async def recent_dialogue(self, bot: str, user: str, limit: int) -> list[str]:
|
||||
rows, _ = await self.messages_page(bot, user, limit)
|
||||
return [f"{role_label(row.get('role'))}: {stored_text(row.get('message_content'))}" for row in reversed(rows)]
|
||||
|
||||
async def full_history(self, bot: str, user: str) -> list[dict]:
|
||||
rows, total = await self.messages_page(bot, user, PAGE_SIZE)
|
||||
collected = list(rows)
|
||||
offset = len(rows)
|
||||
while offset < min(total, MAX_TRANSCRIPT_MESSAGES) and rows:
|
||||
rows, _ = await self.messages_page(bot, user, PAGE_SIZE, offset)
|
||||
collected.extend(rows)
|
||||
offset += len(rows)
|
||||
return list(reversed(collected))
|
||||
|
||||
# ---- LLM -----------------------------------------------------------------
|
||||
|
||||
async def ask_llm(self, model: str, system: str, user_text: str) -> dict:
|
||||
response = await self.invoke_llm(
|
||||
llm_model_uuid=model,
|
||||
messages=[
|
||||
Message(role="system", content=[ContentElement.from_text(system)]),
|
||||
Message(role="user", content=[ContentElement.from_text(user_text)]),
|
||||
],
|
||||
)
|
||||
return parse_json_object(response_text(response))
|
||||
|
||||
async def evaluate_intent(self, config: dict, dialogue: list[str]) -> tuple[bool, str]:
|
||||
criteria = str(config.get("intent_prompt") or DEFAULT_INTENT_PROMPT).strip()
|
||||
system = (
|
||||
"你是销售线索分析助手。请根据「判断标准」阅读客户与 AI 客服的对话,判断客户当前是否有强烈购买意愿。\n"
|
||||
"只输出一个 JSON 对象,不要输出其他内容:{\"strong_intent\": true 或 false, \"reason\": \"一句话理由\"}\n\n"
|
||||
f"判断标准:\n{criteria}"
|
||||
)
|
||||
result = await self.ask_llm(str(config["model"]), system, "对话记录(从旧到新):\n" + "\n".join(dialogue))
|
||||
strong = result.get("strong_intent")
|
||||
if isinstance(strong, str):
|
||||
strong = strong.strip().lower() in ("true", "yes", "1", "是")
|
||||
return bool(strong), str(result.get("reason") or "").strip()
|
||||
|
||||
async def extract_contact(self, config: dict, text: str) -> str:
|
||||
contact = find_contact(text)
|
||||
if contact or not text.strip():
|
||||
return contact
|
||||
system = (
|
||||
"从客户的这条消息中提取联系方式(手机号、电话、微信号、邮箱、QQ 号等)。"
|
||||
"只输出 JSON:{\"contact\": \"联系方式,多个用;分隔,没有则为空字符串\"}。"
|
||||
"不要编造,消息里没有明确的联系方式时返回空字符串。"
|
||||
)
|
||||
try:
|
||||
result = await self.ask_llm(str(config["model"]), system, text)
|
||||
except Exception as error:
|
||||
logger.warning("LeadCapture contact extraction failed: %s", type(error).__name__)
|
||||
return ""
|
||||
return str(result.get("contact") or "").strip()
|
||||
|
||||
# ---- email -----------------------------------------------------------------
|
||||
|
||||
def build_email(self, config: dict, lead: dict, history: list[dict]) -> dict:
|
||||
bot_name = next((row.get("bot_name") for row in history if row.get("bot_name")), "") or lead["bot"]
|
||||
first = utc_label(history[0].get("timestamp")) if history else "-"
|
||||
lines = [
|
||||
f"[{utc_label(row.get('timestamp'))} UTC] {role_label(row.get('role'))}: {stored_text(row.get('message_content'))}"
|
||||
for row in history
|
||||
]
|
||||
summary = [
|
||||
("联系方式", lead["contact"]),
|
||||
("用户 ID", lead["user"]),
|
||||
("来源 Bot", bot_name),
|
||||
("意向判断理由", lead.get("reason") or "-"),
|
||||
("留资时间 (UTC)", utc_label(datetime.fromtimestamp(lead["captured_at"], UTC).isoformat())),
|
||||
("首次联系 (UTC)", first),
|
||||
("消息总数", str(len(history))),
|
||||
]
|
||||
text_body = "\n".join(f"{name}:{value}" for name, value in summary)
|
||||
text_body += "\n\n完整对话记录见附件;以下为全文:\n\n" + "\n".join(lines)
|
||||
html_rows = "".join(
|
||||
f"<tr><td style='padding:4px 12px 4px 0;color:#666'>{html.escape(name)}</td>"
|
||||
f"<td style='padding:4px 0'>{html.escape(value)}</td></tr>"
|
||||
for name, value in summary
|
||||
)
|
||||
html_lines = "".join(f"<div style='margin:2px 0'>{html.escape(line)}</div>" for line in lines)
|
||||
html_body = (
|
||||
"<h2 style='margin:0 0 12px'>新的购买意向线索</h2>"
|
||||
f"<table style='border-collapse:collapse'>{html_rows}</table>"
|
||||
"<h3 style='margin:20px 0 8px'>对话记录</h3>"
|
||||
f"<div style='font-family:monospace;font-size:13px;white-space:pre-wrap'>{html_lines}</div>"
|
||||
)
|
||||
transcript = "\n".join(lines).encode("utf-8")
|
||||
stamp = datetime.fromtimestamp(lead["captured_at"], UTC).strftime("%Y%m%d-%H%M%S")
|
||||
return {
|
||||
"from": str(config.get("from_email") or "").strip(),
|
||||
"to": [address.strip() for address in config.get("to_emails", []) if str(address).strip()],
|
||||
"subject": f"【购买意向】{lead['contact']} · {bot_name}",
|
||||
"text": text_body,
|
||||
"html": html_body,
|
||||
"attachments": [{
|
||||
"filename": f"conversation-{stamp}.txt",
|
||||
"content": base64.b64encode(transcript).decode("ascii"),
|
||||
}],
|
||||
}
|
||||
|
||||
async def send_email(self, config: dict, payload: dict) -> str:
|
||||
"""Send through Resend; returns '' on success or a short error code (never the API key)."""
|
||||
api_key = str(config.get("resend_api_key") or "").strip()
|
||||
if not api_key or not payload["from"] or not payload["to"]:
|
||||
return "not_configured"
|
||||
try:
|
||||
async with httpx.AsyncClient(timeout=30) as client:
|
||||
response = await client.post(
|
||||
RESEND_URL, json=payload, headers={"Authorization": f"Bearer {api_key}"},
|
||||
)
|
||||
except httpx.HTTPError as error:
|
||||
return f"network:{type(error).__name__}"
|
||||
if response.status_code >= 300:
|
||||
try:
|
||||
name = str(response.json().get("name") or "")
|
||||
except ValueError:
|
||||
name = ""
|
||||
return f"http_{response.status_code}" + (f":{name}" if name else "")
|
||||
return ""
|
||||
|
||||
async def deliver(self, config: dict, lead: dict) -> None:
|
||||
"""Email the lead; record the outcome on the lead row."""
|
||||
lead["email_attempts"] = int(lead.get("email_attempts", 0)) + 1
|
||||
try:
|
||||
history = await self.full_history(lead["bot"], lead["user"])
|
||||
except Exception as error:
|
||||
lead["email_status"] = f"history:{'permission_denied' if permission_denied(error) else type(error).__name__}"
|
||||
logger.warning("LeadCapture could not read the conversation: %s", lead["email_status"])
|
||||
return
|
||||
error = await self.send_email(config, self.build_email(config, lead, history))
|
||||
lead["email_status"] = error or "sent"
|
||||
if error:
|
||||
logger.warning("LeadCapture email failed (%s), attempt %s", error, lead["email_attempts"])
|
||||
|
||||
# ---- events --------------------------------------------------------------------
|
||||
|
||||
@staticmethod
|
||||
def configured(config: dict) -> bool:
|
||||
return bool(config.get("model"))
|
||||
|
||||
async def on_person_message(self, event_context) -> None:
|
||||
"""While waiting for contact details, look for them in each user message."""
|
||||
config = self.get_config()
|
||||
if not self.configured(config):
|
||||
return
|
||||
bot = str(await event_context.get_bot_uuid() or "")
|
||||
if not bot:
|
||||
return
|
||||
event = event_context.event
|
||||
user = str(event.sender_id)
|
||||
async with self.lock():
|
||||
key = self.key(bot, user)
|
||||
lead = await self.load(key)
|
||||
if not lead or lead.get("status") != "asked":
|
||||
return
|
||||
contact = await self.extract_contact(config, plain_text(event.message_chain))
|
||||
if not contact:
|
||||
return
|
||||
lead.update(status="captured", contact=contact, captured_at=time.time(), thanks_pending=True)
|
||||
await self.save(key, lead)
|
||||
await self.deliver(config, lead)
|
||||
await self.save(key, lead)
|
||||
|
||||
async def on_responded(self, event_context) -> None:
|
||||
"""After each AI reply: judge intent and ask once, or append the thank-you."""
|
||||
config = self.get_config()
|
||||
event = event_context.event
|
||||
if not self.configured(config) or str(event.launcher_type) != "person":
|
||||
return
|
||||
bot = str(await event_context.get_bot_uuid() or "")
|
||||
if not bot:
|
||||
return
|
||||
user = str(event.sender_id)
|
||||
async with self.lock():
|
||||
key = self.key(bot, user)
|
||||
lead = await self.load(key)
|
||||
if lead and lead.get("status") == "captured":
|
||||
if lead.get("email_status") != "sent" and int(lead.get("email_attempts", 0)) < MAX_EMAIL_ATTEMPTS:
|
||||
await self.deliver(config, lead)
|
||||
if lead.pop("thanks_pending", False):
|
||||
self.append_to_reply(event_context, str(config.get("thanks_text", DEFAULT_THANKS_TEXT) or ""))
|
||||
await self.save(key, lead)
|
||||
return
|
||||
if lead:
|
||||
return # Already asked once; never ask again.
|
||||
try:
|
||||
history = int(config.get("history_messages", 20))
|
||||
except (TypeError, ValueError):
|
||||
history = 20
|
||||
try:
|
||||
dialogue = await self.recent_dialogue(bot, user, max(1, min(history, 100)))
|
||||
except Exception as error:
|
||||
logger.warning("LeadCapture could not read recent messages: %s", type(error).__name__)
|
||||
return
|
||||
dialogue.append(f"AI: {event.response_text}")
|
||||
try:
|
||||
strong, reason = await self.evaluate_intent(config, dialogue)
|
||||
except Exception as error:
|
||||
logger.warning("LeadCapture intent evaluation failed: %s", type(error).__name__)
|
||||
return
|
||||
if not strong:
|
||||
return
|
||||
await self.save(key, {"status": "asked", "bot": bot, "user": user, "reason": reason, "asked_at": time.time()})
|
||||
self.append_to_reply(event_context, str(config.get("ask_text") or DEFAULT_ASK_TEXT))
|
||||
|
||||
@staticmethod
|
||||
def append_to_reply(event_context, text: str) -> None:
|
||||
text = text.strip()
|
||||
if not text:
|
||||
return
|
||||
event = event_context.event
|
||||
base = list(event.reply_message_chain) if event.reply_message_chain is not None else [
|
||||
message.Plain(text=event.response_text)
|
||||
]
|
||||
event.reply_message_chain = message.MessageChain([*base, message.Plain(text=f"\n\n{text}")])
|
||||
@@ -0,0 +1,114 @@
|
||||
apiVersion: v1
|
||||
kind: Plugin
|
||||
metadata:
|
||||
author: langbot-team
|
||||
name: LeadCapture
|
||||
repository: https://github.com/langbot-app/LangBot/tree/master/plugins/misc/LeadCapture
|
||||
version: 0.1.0
|
||||
description:
|
||||
en_US: "Let an LLM spot customers with strong purchase intent, ask them once for contact details, and email the lead with the full conversation via Resend."
|
||||
zh_Hans: "由 LLM 根据对话和提示词判断用户是否有强烈购买意愿,只请求一次联系方式,并通过 Resend 把线索和完整对话发到指定邮箱。"
|
||||
zh_Hant: "由 LLM 根據對話與提示詞判斷使用者是否有強烈購買意願,只請求一次聯絡方式,並透過 Resend 將線索與完整對話寄到指定信箱。"
|
||||
ja_JP: "LLM が会話から強い購入意向を判定し、連絡先を一度だけ尋ね、Resend でリードと会話全文をメール送信します。"
|
||||
es_ES: "Un LLM detecta clientes con fuerte intención de compra, les pide el contacto una vez y envía el cliente con la conversación completa por Resend."
|
||||
ru_RU: "LLM определяет клиентов с сильным намерением купить, один раз просит контакты и отправляет лид с полной перепиской через Resend."
|
||||
th_TH: "ให้ LLM ตรวจหาลูกค้าที่ตั้งใจซื้อสูง ขอช่องทางติดต่อหนึ่งครั้ง แล้วส่งข้อมูลพร้อมบทสนทนาทั้งหมดทางอีเมลผ่าน Resend"
|
||||
vi_VN: "LLM nhận diện khách hàng có ý định mua mạnh, hỏi liên hệ một lần và gửi khách hàng tiềm năng kèm toàn bộ hội thoại qua Resend."
|
||||
label:
|
||||
en_US: Purchase Intent Lead Capture
|
||||
zh_Hans: 购买意向留资
|
||||
zh_Hant: 購買意向留資
|
||||
ja_JP: 購入意向リード獲得
|
||||
es_ES: Captación por intención de compra
|
||||
ru_RU: Сбор лидов по намерению купить
|
||||
th_TH: เก็บลีดตามความตั้งใจซื้อ
|
||||
vi_VN: Thu thập khách hàng theo ý định mua
|
||||
icon: assets/icon.svg
|
||||
spec:
|
||||
permissions:
|
||||
capabilities: [models.invoke, storage.plugin]
|
||||
workspace_operations:
|
||||
- monitoring.messages
|
||||
config:
|
||||
- name: model
|
||||
type: llm-model-selector
|
||||
required: true
|
||||
label:
|
||||
en_US: Model for judging intent
|
||||
zh_Hans: 判断用的模型
|
||||
description:
|
||||
en_US: Used to judge purchase intent and to read contact details that patterns cannot find.
|
||||
zh_Hans: 用来判断购买意愿,以及在规则识别不到时识别联系方式。
|
||||
- name: intent_prompt
|
||||
type: text
|
||||
default: "用户明确表达了购买、下单、试用、报价、签约、采购或与销售沟通的意愿,或在询问价格、套餐、付款方式、发票、合同、交付时间等成交相关细节,视为强烈购买意愿。只是了解产品功能、闲聊或技术咨询,不算强烈购买意愿。"
|
||||
label:
|
||||
en_US: Intent criteria (prompt)
|
||||
zh_Hans: 购买意愿判断标准(提示词)
|
||||
description:
|
||||
en_US: Describe what counts as strong purchase intent for your business. The plugin adds the conversation and asks for a yes/no answer.
|
||||
zh_Hans: 描述在你们业务里什么算强烈购买意愿。插件会附上对话并要求模型给出是/否结论。
|
||||
- name: history_messages
|
||||
type: integer
|
||||
default: 20
|
||||
label:
|
||||
en_US: Messages used for judging
|
||||
zh_Hans: 参与判断的对话条数
|
||||
description:
|
||||
en_US: How many recent messages (user and AI) the model reads each time, up to 100.
|
||||
zh_Hans: 每次判断时读取最近多少条对话(含用户和 AI),最多 100。
|
||||
- name: ask_text
|
||||
type: text
|
||||
default: "为了更好地为您服务,方便留下您的手机号或微信号吗?我们的顾问会尽快与您联系。"
|
||||
label:
|
||||
en_US: Contact request text
|
||||
zh_Hans: 请求联系方式的话术
|
||||
description:
|
||||
en_US: Appended to the AI reply once, when strong intent is detected.
|
||||
zh_Hans: 判断为强烈购买意愿时,附加在该次 AI 回复后面,每个用户只发一次。
|
||||
- name: thanks_text
|
||||
type: text
|
||||
default: "已收到您的联系方式,我们的顾问会尽快与您联系,感谢您的信任!"
|
||||
label:
|
||||
en_US: Thank-you text
|
||||
zh_Hans: 收到联系方式后的致谢
|
||||
description:
|
||||
en_US: Appended to the next AI reply after contact details are received. Leave empty to disable.
|
||||
zh_Hans: 收到联系方式后附加在下一次 AI 回复后面。留空则不发送。
|
||||
- name: resend_api_key
|
||||
type: secret
|
||||
required: true
|
||||
label:
|
||||
en_US: Resend API key
|
||||
zh_Hans: Resend API Key
|
||||
description:
|
||||
en_US: Create one at resend.com → API Keys (Sending access is enough).
|
||||
zh_Hans: 在 resend.com → API Keys 创建,选 Sending access 即可。
|
||||
- name: from_email
|
||||
type: string
|
||||
required: true
|
||||
label:
|
||||
en_US: Sender address
|
||||
zh_Hans: 发件地址
|
||||
description:
|
||||
en_US: "An address on a domain verified in Resend, e.g. [email protected] or \"Leads <[email protected]>\"."
|
||||
zh_Hans: "必须是在 Resend 验证过的域名下的地址,例如 [email protected] 或 \"销售线索 <[email protected]>\"。"
|
||||
- name: to_emails
|
||||
type: array[string]
|
||||
default: []
|
||||
label:
|
||||
en_US: Recipient addresses
|
||||
zh_Hans: 收件邮箱
|
||||
description:
|
||||
en_US: One or more addresses that receive each lead.
|
||||
zh_Hans: 接收线索的邮箱,可填多个。
|
||||
components:
|
||||
EventListener:
|
||||
fromDirs:
|
||||
- path: components/event_listener/
|
||||
execution:
|
||||
python:
|
||||
path: main.py
|
||||
attr: LeadCapture
|
||||
sharedRuntime: shared-runtime-v1
|
||||
componentModel: stateless-v1
|
||||
@@ -0,0 +1,2 @@
|
||||
[pytest]
|
||||
asyncio_default_fixture_loop_scope = function
|
||||
@@ -0,0 +1,106 @@
|
||||
# 购买意向留资
|
||||
|
||||
让 AI 客服自动发现「想买」的客户:插件在每次 AI 回复后,用你选定的模型、按你写的判断标准阅读对话,判断客户是否有**强烈购买意愿**。一旦判定为是,就在这次回复后面附上一句请求联系方式的话术(每个客户只问一次);客户留下手机号 / 微信 / 邮箱后,插件把**联系方式 + 与该客户的全部对话记录**通过 [Resend](https://resend.com) 发到你指定的邮箱。
|
||||
|
||||
适用于任意平台的私聊(微信公众号、企业微信客服、Telegram、QQ……)。
|
||||
|
||||
## 效果一览
|
||||
|
||||
1. 客户和 AI 正常聊天,例如问「年付多少钱?能开发票吗?」
|
||||
2. AI 回复后,插件判断为强烈购买意愿,这次回复末尾多一句:「为了更好地为您服务,方便留下您的手机号或微信号吗?我们的顾问会尽快与您联系。」
|
||||
3. 客户回复「138 0013 8000」。插件识别到联系方式,立刻发出一封邮件:
|
||||
- 标题:`【购买意向】138 0013 8000 · 微信公众号`
|
||||
- 正文:联系方式、用户 ID、来源 Bot、意向判断理由、留资时间、首次联系时间、消息总数,以及完整对话;
|
||||
- 附件:`conversation-时间.txt`(完整对话记录)。
|
||||
4. 下一次 AI 回复末尾附上致谢:「已收到您的联系方式,我们的顾问会尽快与您联系,感谢您的信任!」
|
||||
5. 之后不再判断、不再追问这个客户。如果客户没留联系方式,也不会再问第二次。
|
||||
|
||||
## 配置步骤
|
||||
|
||||
### 第 1 步:准备 Resend
|
||||
|
||||
1. 注册 [resend.com](https://resend.com)。
|
||||
2. **Domains → Add Domain**,添加你们自己的发信域名(例如 `example.com`),按提示在域名 DNS 里添加记录,等状态变为 **Verified**。
|
||||
3. **API Keys → Create API Key**,权限选 **Sending access**,复制生成的 `re_` 开头的 Key(只显示一次)。
|
||||
|
||||
> 未验证域名时,Resend 只允许用 `[email protected]` 发给注册 Resend 的那个邮箱,仅适合测试。
|
||||
|
||||
### 第 2 步:安装插件并确认权限
|
||||
|
||||
安装后在插件详情页**确认权限**:
|
||||
|
||||
| 权限 | 用途 |
|
||||
| --- | --- |
|
||||
| `models.invoke` | 调用模型判断购买意愿、识别联系方式 |
|
||||
| `storage.plugin` | 记录每个客户「已询问 / 已留资」的状态 |
|
||||
| `monitoring.messages`(消息历史查询,只读) | 读取对话记录,用于判断和发送邮件 |
|
||||
|
||||
### 第 3 步:填写插件配置
|
||||
|
||||
| 配置项 | 填什么 |
|
||||
| --- | --- |
|
||||
| 判断用的模型 | 选一个对话模型。每次 AI 回复后都会调用一次,建议选响应快、成本低的模型 |
|
||||
| 购买意愿判断标准(提示词) | 用自然语言描述在你们业务里什么算强烈购买意愿,例如「询问价格、套餐、合同、发票、试用、上线时间」算,「只问功能、闲聊」不算。已有一份通用默认值 |
|
||||
| 参与判断的对话条数 | 每次判断读取最近多少条对话,默认 20,最多 100 |
|
||||
| 请求联系方式的话术 | 判定为强烈意愿时附加在 AI 回复后的固定文案 |
|
||||
| 收到联系方式后的致谢 | 留资后附加在下一次 AI 回复后的文案,留空则不发 |
|
||||
| Resend API Key | 第 1 步的 `re_` 开头的 Key |
|
||||
| 发件地址 | 已验证域名下的地址,例如 `[email protected]`,也可以写成 `销售线索 <[email protected]>` |
|
||||
| 收件邮箱 | 接收线索的邮箱,可填多个 |
|
||||
|
||||
### 第 4 步:在流水线中启用
|
||||
|
||||
插件在流水线里工作:确认客户聊天用的 Bot 收到消息后交给一条**流水线**处理,并且这条流水线允许使用本插件。
|
||||
|
||||
### 第 5 步:测试
|
||||
|
||||
用自己的账号和 Bot 聊天,问一些和购买相关的问题(价格、合同、试用),看 AI 回复末尾是否出现请求话术;回复一个手机号,检查收件邮箱。
|
||||
|
||||
## 联系方式怎么识别
|
||||
|
||||
- 先用规则识别:中国大陆手机号(可带 `+86`、空格或横线)、带区号的座机(如 `010-12345678`)、邮箱、「微信 / vx / wx」后面的微信号。
|
||||
- 规则识别不到时,再让模型从这条消息里提取(例如「加我 QQ 123456789」)。模型被要求不得编造,没有联系方式时返回空。
|
||||
- 识别到之前,客户的每条消息都会检查一次;之后不再检查。
|
||||
|
||||
## 常见问题
|
||||
|
||||
**邮件没收到**
|
||||
查看插件日志中的 `LeadCapture email failed (...)`:
|
||||
- `not_configured`:API Key、发件地址或收件邮箱没填。
|
||||
- `http_403:validation_error`:发件域名还没在 Resend 验证,或发件地址不在该域名下。
|
||||
- `http_401` / `http_403`:API Key 错误或权限不足。
|
||||
- `network:...`:服务器无法连到 `api.resend.com`。
|
||||
|
||||
发送失败后,会在之后的 AI 回复时自动重试,**最多共 3 次**。
|
||||
|
||||
**一直没有出现请求话术**
|
||||
确认模型已选择、判断标准写得足够具体;也可以在插件日志里查看是否有 `intent evaluation failed`。已经问过一次的客户不会再问。
|
||||
|
||||
**AI 回复变慢了**
|
||||
每次 AI 回复后要额外调用一次模型做判断,会增加这次回复的耗时(通常 1~3 秒)。可以换更快的模型,或减少参与判断的对话条数。微信公众号 auto 模式下回复本就是异步推送,影响不明显。
|
||||
|
||||
**AI 回复里的图片**
|
||||
附加话术时,这次回复会以文字形式发送;如果 AI 的这条回复含图片,图片会显示为占位文字。
|
||||
|
||||
## 限制与说明
|
||||
|
||||
- 只处理私聊,不处理群聊。
|
||||
- 每个客户只询问一次联系方式;状态按「Bot + 用户」保存。重装插件会清空所有客户的状态。
|
||||
- 邮件中包含客户的联系方式和完整对话,请确认符合你们的隐私与数据管理要求。
|
||||
- 对话记录来自 LangBot 的消息记录,最多导出 5000 条。
|
||||
|
||||
## 给开发者
|
||||
|
||||
一个 EventListener(`components/event_listener/lead.py`):
|
||||
|
||||
- `NormalMessageResponded`:判断意愿,并通过 `reply_message_chain` 在 AI 回复后附加请求话术或致谢;
|
||||
- `PersonMessageReceived`:在已询问状态下识别联系方式,并调用 Resend 发送邮件。
|
||||
|
||||
对话来自只读的 `monitoring.messages` Workspace 操作;任何失败都只记录日志,不会影响对话本身。
|
||||
|
||||
```bash
|
||||
uv venv
|
||||
uv pip install -r requirements-dev.txt
|
||||
uv run pytest -q
|
||||
uv run ruff check .
|
||||
```
|
||||
@@ -0,0 +1,6 @@
|
||||
langbot-plugin @ git+https://github.com/langbot-app/langbot-plugin-sdk@7cc07a18081fe153a42431b28dd9118d08ffa4d6
|
||||
pytest
|
||||
pytest-asyncio
|
||||
PyYAML
|
||||
ruff
|
||||
httpx
|
||||
@@ -0,0 +1 @@
|
||||
httpx
|
||||
@@ -0,0 +1,323 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import base64
|
||||
import importlib.util
|
||||
import json
|
||||
import sys
|
||||
from pathlib import Path
|
||||
from types import SimpleNamespace
|
||||
from unittest.mock import AsyncMock
|
||||
|
||||
import httpx
|
||||
import pytest
|
||||
import yaml
|
||||
from langbot_plugin.api.entities import events
|
||||
from langbot_plugin.api.entities.builtin.platform import message
|
||||
from langbot_plugin.api.proxies.invocation import bind_invocation
|
||||
from langbot_plugin.entities.io.actions.enums import PluginToRuntimeAction as Action
|
||||
from langbot_plugin.entities.io.context import InstallationBinding
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
|
||||
|
||||
def load_module(path, name):
|
||||
spec = importlib.util.spec_from_file_location(name, path)
|
||||
module = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(module)
|
||||
return module
|
||||
|
||||
|
||||
lead_main = load_module(ROOT / "main.py", "lead_capture_main")
|
||||
sys.modules["main"] = lead_main
|
||||
listener_module = load_module(ROOT / "components/event_listener/lead.py", "lead_capture_listener")
|
||||
|
||||
CONFIG = {
|
||||
"model": "model-1", "intent_prompt": "asks for a quote", "history_messages": 20,
|
||||
"ask_text": "ASK-CONTACT", "thanks_text": "THANKS",
|
||||
"resend_api_key": "re_secret_key", "from_email": "Leads <[email protected]>",
|
||||
"to_emails": ["[email protected]", " ", "[email protected]"],
|
||||
}
|
||||
USER = "openid-user-1"
|
||||
|
||||
|
||||
class Host:
|
||||
def __init__(self):
|
||||
self.storage = {}
|
||||
self.history = [] # oldest first
|
||||
self.llm_answers = []
|
||||
self.llm_calls = []
|
||||
self.operations = []
|
||||
|
||||
async def call_action(self, action, data, *args, **kwargs):
|
||||
if action == Action.GET_PLUGIN_STORAGE_KEYS:
|
||||
return {"keys": list(self.storage)}
|
||||
if action == Action.GET_PLUGIN_STORAGE:
|
||||
return {"value_base64": base64.b64encode(self.storage[data["key"]]).decode()}
|
||||
if action == Action.SET_PLUGIN_STORAGE:
|
||||
self.storage[data["key"]] = base64.b64decode(data["value_base64"])
|
||||
return {}
|
||||
if action == Action.CALL_APPLICATION_OPERATION:
|
||||
self.operations.append(data)
|
||||
args = data["arguments"]
|
||||
newest_first = list(reversed(self.history))
|
||||
rows = newest_first[args["offset"]:args["offset"] + args["limit"]]
|
||||
return {"ok": True, "result": [rows, len(self.history)]}
|
||||
if action == Action.INVOKE_LLM:
|
||||
self.llm_calls.append(data)
|
||||
answer = self.llm_answers.pop(0) if self.llm_answers else "{}"
|
||||
return {"message": {"role": "assistant", "content": answer}}
|
||||
raise AssertionError(f"Unexpected action: {action}")
|
||||
|
||||
|
||||
def binding():
|
||||
return InstallationBinding(
|
||||
instance_uuid="instance-1", workspace_uuid="workspace-1", installation_uuid="install-1",
|
||||
placement_generation=1, runtime_revision=1, artifact_digest="a" * 64,
|
||||
)
|
||||
|
||||
|
||||
def row(role, text, ts="2026-11-06T07:00:00"):
|
||||
return {"role": role, "bot_name": "微信公众号", "timestamp": ts,
|
||||
"message_content": json.dumps([{"type": "Plain", "text": text}])}
|
||||
|
||||
|
||||
def received(text, user=USER):
|
||||
return SimpleNamespace(
|
||||
event=SimpleNamespace(
|
||||
launcher_type="person", launcher_id=user, sender_id=user,
|
||||
message_chain=message.MessageChain([message.Plain(text=text)]),
|
||||
),
|
||||
get_bot_uuid=AsyncMock(return_value="bot-1"),
|
||||
)
|
||||
|
||||
|
||||
def responded(text="AI answer", user=USER):
|
||||
event = SimpleNamespace(
|
||||
launcher_type="person", launcher_id=user, sender_id=user,
|
||||
response_text=text, reply_message_chain=None,
|
||||
)
|
||||
return SimpleNamespace(event=event, get_bot_uuid=AsyncMock(return_value="bot-1"))
|
||||
|
||||
|
||||
def reply_text(ctx):
|
||||
chain = ctx.event.reply_message_chain
|
||||
return None if chain is None else "".join(part.text for part in chain if isinstance(part, message.Plain))
|
||||
|
||||
|
||||
class Resend:
|
||||
def __init__(self, status=200, body=None):
|
||||
self.requests = []
|
||||
self.status = status
|
||||
self.body = body or {"id": "email-1"}
|
||||
|
||||
def install(self, monkeypatch):
|
||||
transport = httpx.MockTransport(self.handle)
|
||||
original = httpx.AsyncClient
|
||||
|
||||
def client(*args, **kwargs):
|
||||
kwargs["transport"] = transport
|
||||
return original(*args, **kwargs)
|
||||
|
||||
monkeypatch.setattr(lead_main.httpx, "AsyncClient", client)
|
||||
return self
|
||||
|
||||
def handle(self, request):
|
||||
self.requests.append(request)
|
||||
return httpx.Response(self.status, json=self.body)
|
||||
|
||||
|
||||
async def graph():
|
||||
host = Host()
|
||||
plugin = lead_main.LeadCapture()
|
||||
plugin.plugin_runtime_handler = host
|
||||
listener = listener_module.LeadListener()
|
||||
listener.plugin = plugin
|
||||
await listener.initialize()
|
||||
handlers = listener.registered_handlers
|
||||
return plugin, host, handlers
|
||||
|
||||
|
||||
async def fire(handlers, event_type, ctx):
|
||||
await handlers[event_type][0](ctx)
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_no_intent_leaves_reply_untouched():
|
||||
_plugin, host, handlers = await graph()
|
||||
host.history = [row("user", "what does it do?")]
|
||||
host.llm_answers = ['{"strong_intent": false, "reason": "just browsing"}']
|
||||
ctx = responded()
|
||||
with bind_invocation(host, config=CONFIG, binding=binding()):
|
||||
await fire(handlers, events.NormalMessageResponded, ctx)
|
||||
assert reply_text(ctx) is None
|
||||
assert host.storage == {}
|
||||
prompt = host.llm_calls[0]["messages"]
|
||||
assert "asks for a quote" in json.dumps(prompt, ensure_ascii=False)
|
||||
assert "AI: AI answer" in json.dumps(prompt, ensure_ascii=False)
|
||||
assert host.operations[0]["arguments"]["session_ids"] == [f"person_{USER}"]
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_strong_intent_appends_ask_once():
|
||||
_plugin, host, handlers = await graph()
|
||||
host.history = [row("user", "how much is the annual plan?")]
|
||||
host.llm_answers = ['```json\n{"strong_intent": true, "reason": "asked price"}\n```']
|
||||
first = responded("The annual plan is $99.")
|
||||
second = responded("Anything else?")
|
||||
with bind_invocation(host, config=CONFIG, binding=binding()):
|
||||
await fire(handlers, events.NormalMessageResponded, first)
|
||||
await fire(handlers, events.NormalMessageResponded, second)
|
||||
assert reply_text(first) == "The annual plan is $99.\n\nASK-CONTACT"
|
||||
assert reply_text(second) is None
|
||||
assert len(host.llm_calls) == 1 # never re-evaluated after asking
|
||||
state = json.loads(next(iter(host.storage.values())))
|
||||
assert state["status"] == "asked" and state["reason"] == "asked price"
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_existing_plugin_reply_is_preserved_when_appending():
|
||||
_plugin, host, handlers = await graph()
|
||||
host.llm_answers = ['{"strong_intent": "true"}']
|
||||
ctx = responded("original")
|
||||
ctx.event.reply_message_chain = message.MessageChain([message.Plain(text="rewritten by another plugin")])
|
||||
with bind_invocation(host, config=CONFIG, binding=binding()):
|
||||
await fire(handlers, events.NormalMessageResponded, ctx)
|
||||
assert reply_text(ctx) == "rewritten by another plugin\n\nASK-CONTACT"
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_contact_capture_emails_full_history_and_thanks_once(monkeypatch):
|
||||
resend = Resend().install(monkeypatch)
|
||||
_plugin, host, handlers = await graph()
|
||||
host.history = [row("user", f"msg {i}", f"2026-11-0{1 + i // 200}T00:00:{i % 60:02d}") for i in range(230)]
|
||||
host.llm_answers = ['{"strong_intent": true, "reason": "wants to buy"}']
|
||||
with bind_invocation(host, config=CONFIG, binding=binding()):
|
||||
await fire(handlers, events.NormalMessageResponded, responded())
|
||||
await fire(handlers, events.PersonMessageReceived, received("我的手机 138 0013 8000,微信 abc_12345"))
|
||||
after = responded("Noted.")
|
||||
await fire(handlers, events.NormalMessageResponded, after)
|
||||
later = responded("Bye.")
|
||||
await fire(handlers, events.NormalMessageResponded, later)
|
||||
assert len(host.llm_calls) == 1 # contact found by pattern, no extraction call
|
||||
assert len(resend.requests) == 1
|
||||
request = resend.requests[0]
|
||||
assert request.headers["Authorization"] == "Bearer re_secret_key"
|
||||
payload = json.loads(request.content)
|
||||
assert payload["from"] == "Leads <[email protected]>"
|
||||
assert payload["to"] == ["[email protected]", "[email protected]"]
|
||||
assert "138 0013 8000" in payload["subject"] and "微信: abc_12345" in payload["subject"]
|
||||
assert "wants to buy" in payload["text"] and "消息总数:230" in payload["text"]
|
||||
transcript = base64.b64decode(payload["attachments"][0]["content"]).decode()
|
||||
assert transcript.count("\n") == 229 and transcript.startswith("[2026-11-01 00:00:00 UTC] 用户: msg 0")
|
||||
assert "re_secret_key" not in payload["text"] + payload["html"]
|
||||
assert reply_text(after) == "Noted.\n\nTHANKS"
|
||||
assert reply_text(later) is None
|
||||
state = json.loads(next(iter(host.storage.values())))
|
||||
assert state["status"] == "captured" and state["email_status"] == "sent"
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_llm_extracts_contact_when_patterns_miss(monkeypatch):
|
||||
resend = Resend().install(monkeypatch)
|
||||
_plugin, host, handlers = await graph()
|
||||
host.llm_answers = ['{"strong_intent": true}', '{"contact": "QQ 123456789"}']
|
||||
with bind_invocation(host, config=CONFIG, binding=binding()):
|
||||
await fire(handlers, events.NormalMessageResponded, responded())
|
||||
await fire(handlers, events.PersonMessageReceived, received("加我扣扣一二三四五六七八九吧 就是 123456789"))
|
||||
assert len(resend.requests) == 1
|
||||
assert "QQ 123456789" in json.loads(resend.requests[0].content)["subject"]
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_messages_without_contact_keep_waiting(monkeypatch):
|
||||
resend = Resend().install(monkeypatch)
|
||||
_plugin, host, handlers = await graph()
|
||||
host.llm_answers = ['{"strong_intent": true}', '{"contact": ""}']
|
||||
with bind_invocation(host, config=CONFIG, binding=binding()):
|
||||
await fire(handlers, events.NormalMessageResponded, responded())
|
||||
await fire(handlers, events.PersonMessageReceived, received("我再考虑一下"))
|
||||
assert resend.requests == []
|
||||
assert json.loads(next(iter(host.storage.values())))["status"] == "asked"
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_email_failure_is_retried_on_later_replies(monkeypatch):
|
||||
resend = Resend(status=403, body={"name": "validation_error", "message": "domain not verified"}).install(monkeypatch)
|
||||
_plugin, host, handlers = await graph()
|
||||
host.llm_answers = ['{"strong_intent": true}']
|
||||
with bind_invocation(host, config=CONFIG, binding=binding()):
|
||||
await fire(handlers, events.NormalMessageResponded, responded())
|
||||
await fire(handlers, events.PersonMessageReceived, received("my email is [email protected]"))
|
||||
for _ in range(4):
|
||||
await fire(handlers, events.NormalMessageResponded, responded())
|
||||
state = json.loads(next(iter(host.storage.values())))
|
||||
assert state["email_status"] == "http_403:validation_error"
|
||||
assert state["email_attempts"] == lead_main.MAX_EMAIL_ATTEMPTS
|
||||
assert len(resend.requests) == lead_main.MAX_EMAIL_ATTEMPTS
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_unconfigured_or_group_events_do_nothing():
|
||||
_plugin, host, handlers = await graph()
|
||||
group = responded()
|
||||
group.event.launcher_type = "group"
|
||||
with bind_invocation(host, config=CONFIG, binding=binding()):
|
||||
await fire(handlers, events.NormalMessageResponded, group)
|
||||
with bind_invocation(host, config={**CONFIG, "model": ""}, binding=binding()):
|
||||
await fire(handlers, events.NormalMessageResponded, responded())
|
||||
assert host.llm_calls == [] and host.storage == {}
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_llm_failure_never_breaks_the_reply():
|
||||
_plugin, host, handlers = await graph()
|
||||
|
||||
async def boom(*args, **kwargs):
|
||||
raise RuntimeError("provider down")
|
||||
|
||||
host.call_action, original = boom, host.call_action
|
||||
ctx = responded()
|
||||
with bind_invocation(host, config=CONFIG, binding=binding()):
|
||||
await fire(handlers, events.NormalMessageResponded, ctx)
|
||||
host.call_action = original
|
||||
assert reply_text(ctx) is None
|
||||
|
||||
|
||||
@pytest.mark.parametrize("text,expected", [
|
||||
("电话13800138000", "13800138000"),
|
||||
("+86 138-0013-8000", "+86 138-0013-8000"),
|
||||
("座机 010-12345678", "010-12345678"),
|
||||
("mail me: [email protected]", "[email protected]"),
|
||||
("我的微信号是 wxid_abc123", "微信: wxid_abc123"),
|
||||
("VX:Hello-2024", "微信: Hello-2024"),
|
||||
("订单号 123456789012345", ""),
|
||||
("我再想想", ""),
|
||||
])
|
||||
def test_find_contact(text, expected):
|
||||
assert lead_main.find_contact(text) == expected
|
||||
|
||||
|
||||
def test_send_email_reports_missing_configuration():
|
||||
import asyncio
|
||||
|
||||
plugin = lead_main.LeadCapture()
|
||||
result = asyncio.run(plugin.send_email({"resend_api_key": ""}, {"from": "[email protected]", "to": ["[email protected]"]}))
|
||||
assert result == "not_configured"
|
||||
|
||||
|
||||
def test_manifest():
|
||||
manifest = yaml.safe_load((ROOT / "manifest.yaml").read_text())
|
||||
assert manifest["metadata"]["name"] == "LeadCapture"
|
||||
assert manifest["spec"]["permissions"] == {
|
||||
"capabilities": ["models.invoke", "storage.plugin"], "workspace_operations": ["monitoring.messages"],
|
||||
}
|
||||
names = [item["name"] for item in manifest["spec"]["config"]]
|
||||
assert names == ["model", "intent_prompt", "history_messages", "ask_text", "thanks_text",
|
||||
"resend_api_key", "from_email", "to_emails"]
|
||||
defaults = {item["name"]: item.get("default") for item in manifest["spec"]["config"]}
|
||||
assert defaults["intent_prompt"] == lead_main.DEFAULT_INTENT_PROMPT
|
||||
assert defaults["ask_text"] == lead_main.DEFAULT_ASK_TEXT
|
||||
assert defaults["thanks_text"] == lead_main.DEFAULT_THANKS_TEXT
|
||||
locales = {"en_US", "zh_Hans", "zh_Hant", "ja_JP", "es_ES", "ru_RU", "th_TH", "vi_VN"}
|
||||
assert set(manifest["metadata"]["label"]) == locales
|
||||
assert set(manifest["metadata"]["description"]) == locales
|
||||
Reference in New Issue
Block a user