ThunderPhone 2.0 正式上线。全程自助,2 美分/分钟起。查看发布公告

Developer cookbook

按通话动态配置

通过您控制的 webhook 中的自定义逻辑,为每个呼入电话分别选择接听的智能体,或重写其提示词和设置。

默认情况下,每个电话号码和可发布密钥都分配有一个静态智能体。当您需要进行按来电者按访客的自定义时——例如 VIP 路由、已登录用户上下文、A/B 提示词测试——请切换到 Webhook 模式,让您的服务器作出决定。

工作原理

  1. 订阅 telephony.incoming (电话)或 web.incoming(小组件) 事件。两者都是阻塞式 Webhook:ThunderPhone 会在继续通话前最多等待 10 秒以获取您的响应。
  2. ThunderPhone 会向您发送 {call_id, from_number, to_number}(小组件 会话会携带小组件专用字段而非号码——请参阅 请求架构)。
  3. 您的服务器返回智能体配置(提示词、语音、产品、工具)。ThunderPhone 会将该配置用于此次通话。
  4. 如果您返回 {}、超时或出错,则会回退使用静态分配的智能体。这是安全的默认行为。

1. 配置 Webhook 目标地址

对于电话号码,请将您的端点订阅到 telephony.incoming

curl -X POST https://api.thunderphone.com/v1/developer/webhook-endpoints \
  -H "Authorization: Bearer sk_live_YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "label":  "Prod call-incoming",
    "url":    "https://example.com/thunderphone/incoming",
    "events": ["telephony.incoming"]
  }'

响应中包含一次性的 secret——请保存它;您将使用它进行签名验证。

对于小组件会话,请创建一个 mode="webhook" 的可发布密钥,并在其中内置您的端点 URL:

curl -X POST https://api.thunderphone.com/v1/publishable-key \
  -H "Authorization: Bearer sk_live_YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "name":            "Dynamic widget",
    "mode":            "webhook",
    "webhook_url":     "https://example.com/thunderphone/widget-incoming",
    "allowed_domains": ["example.com"]
  }'

小组件将在每次会话开始时向此 URL 发送 POST 请求。

2. 实现处理程序

三条经验法则:

  • 对每个请求都要验证签名(请参阅 验证 Webhook 签名)。 即使在开发环境中也不要跳过此步骤——一次正确实现后即可复用。
  • 快速响应。十秒是硬性上限,而每一秒对来电者来说都是 无声等待。您可以按需查询数据库,但不要同步调用下游 LLM——如果您需要动态 生成提示词,请预先计算并缓存。
  • 妥善回退。任何意外状态都应返回 {},以便 静态分配的智能体处理该通电话。
FastAPI
import hashlib
import hmac
import json
import os
 
from fastapi import FastAPI, HTTPException, Request
 
app = FastAPI()
SECRET = os.environ["THUNDERPHONE_WEBHOOK_SECRET"]
 
def verify(body: bytes, sig: str) -> bool:
    expected = hmac.new(SECRET.encode(), body, hashlib.sha256).hexdigest()
    return hmac.compare_digest(expected, sig or "")
 
@app.post("/thunderphone/incoming")
async def incoming(request: Request):
    body = await request.body()
    if not verify(body, request.headers.get("X-ThunderPhone-Signature", "")):
        raise HTTPException(401)
 
    event = json.loads(body)
    if event["type"] not in ("telephony.incoming", "web.incoming"):
        return {}  # fall back to default
 
    caller = event["data"]["from_number"]
    # Cheap DB lookup: is this a known VIP?
    customer = lookup_customer(caller)
    if customer and customer.tier == "vip":
        return {
            "prompt":  f"You are a VIP concierge for {customer.name}. Be proactive…",
            "voice":   "john",
            "product": "storm-base",
        }
    return {}  # default agent handles non-VIPs
 
def lookup_customer(phone: str):
    # ... your CRM integration ...
    pass
Express
import crypto from "node:crypto";
import express from "express";
 
const app = express();
const SECRET = process.env.THUNDERPHONE_WEBHOOK_SECRET;
 
function verify(body, sig) {
  const expected = crypto.createHmac("sha256", SECRET).update(body).digest("hex");
  return sig &&
    crypto.timingSafeEqual(Buffer.from(expected), Buffer.from(sig));
}
 
app.post(
  "/thunderphone/incoming",
  express.raw({ type: "application/json" }),
  async (req, res) => {
    if (!verify(req.body, req.header("X-ThunderPhone-Signature"))) {
      return res.sendStatus(401);
    }
    const event = JSON.parse(req.body.toString("utf8"));
 
    const IMPORTANT_TYPES = new Set([
      "telephony.incoming",
      "web.incoming",
    ]);
    if (!IMPORTANT_TYPES.has(event.type)) return res.json({});
 
    const customer = await lookupCustomer(event.data.from_number);
    if (customer?.tier === "vip") {
      return res.json({
        prompt:  `You are a VIP concierge for ${customer.name}. Be proactive…`,
        voice:   "john",
        product: "storm-base",
      });
    }
    res.json({}); // fall back to default agent
  },
);

3. 响应架构

响应正文与 来电响应架构 完全一致。常用字段如下:

字段类型说明
prompt字符串(必填)智能体的系统提示词
voice字符串(必填)来自 GET /v1/voices 的语音 ID
product字符串默认为 spark
background_track字符串 | null环境音频 ID
acknowledgement_prompt_mode字符串automanual(仅适用于带确认的 Storm)
acknowledgement_prompt字符串当模式为 manual 时必填
tools数组内联函数工具架构——请参阅函数工具

模式

已登录用户上下文

在 webhook 模式的小组件中,访客所在的页面已知道其身份。使用小组件 SDK 会转发的查询字符串参数(?customer_id=123)调用您的 webhook,并在服务端查找客户信息。

A/B 提示词发布

在您自行实现之前,请注意 ThunderPhone 提供原生的 实验 功能(/dashboard/experiments 和智能体构建器中的 A/B 选项卡),可定义变体、拆分流量,并按变体比较结果——无需 webhook。

如果您仍需要在 webhook 端进行控制:对 call_id 进行哈希 → 分桶;对 0..49 提供提示词 A,对 50..99 提供提示词 B。将您选择的分桶记录到自己的数据库中,之后与已完成通话的评分进行关联。

基于时间的路由

营业时间 → “实时支持”智能体;非营业时间 → “留言”智能体。在您的处理程序中,基于 new Date().getUTCHours() 进行简单切换即可。


后续步骤