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"]
  }'

小工具會在每次工作階段開始時 POST 至此 URL。

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. 回應結構

回應主體與 來電回應結構 完全一致。常用欄位如下:

欄位類型說明
promptstring(必填)智能體的系統提示
voicestring(必填)來自 GET /v1/voices 的語音 ID
productstring預設為 spark
background_trackstring | null環境音效 ID
acknowledgement_prompt_modestringautomanual(僅限帶確認提示的 Storm)
acknowledgement_promptstring模式為 manual 時必填
toolsarray內嵌函數工具結構——請參閱函數工具

保留已儲存的智能體並提供變數

回傳 {"agent_id": 12, "variables": {"name": "Ada"}},即可使用該機構已儲存的 智能體及單次通話資料。其提示可包含 {{name}}{{name|Friend}}。Webhook 變數會覆蓋請求層級變數;null 會使用預留位置的預設值,如未提供預設值則使用空白文字。最終 值及未解析的名稱會顯示於通話詳情和完成 webhook。已儲存智能體的回應僅接受 agent_idvariables。如包含 prompt, 回應會使用內嵌設定並忽略 agent_id(包括 null 或非整數中繼資料);內嵌提示仍必須有效。內嵌 設定回應亦可包含 variables。已儲存智能體的回應會在電話及小工具通話中使用 智能體已部署的 A/B 分流,然後再呈現變數。請參閱通話變數 了解限制及工作階段 API 支援。攔截設定來自舊版 電話號碼/機構 URL 或 webhook 模式小工具金鑰;端點系統的 來電事件僅作通知用途。

模式

已登入用戶內容

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


下一步