每通來電的動態設定

預設情況下,每個電話號碼和可發佈金鑰都會指派一個靜態智能體。當你需要為每位來電者每位訪客自訂設定——例如 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. 實作處理程式

三項實用原則:

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
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-with-ack)
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() 切換即可。


下一步