ThunderPhone 2.0 正式上線。全程自助,每分鐘 2 美分起查看公告

Webhooks

telephony.incoming / web.incoming

即時設定來電組態的阻塞式 Webhook。

當未指派智慧體的電話號碼收到來電,或網頁小工具工作階段以 mode="webhook" 的可公開金鑰啟動時,ThunderPhone 會向你的 舊版 webhook URL 傳送一個會阻塞的 telephony.incoming / web.incoming 請求,並最多等待 10 秒 取得設定回應。使用此交換流程,為每通電話動態選擇提示詞、語音和工具—— 如需完整流程,請參閱動態通話設定指南

此阻塞交換流程沒有備援:如果你的處理常式回傳非 2xx 狀態、逾時,或回傳 未通過驗證的設定,通話就會被拒絕(電話不會接通;小工具工作階段請求會以 502/422 失敗)。請快速回應——當你做出決定時,來電者正在聽回鈴音。

請求承載資料

電話通話(telephony.incoming):

{
  "type": "telephony.incoming",
  "data": {
    "call_id":     987654321,
    "from_number": "+14155550199",
    "to_number":   "+15551234567"
  }
}
欄位類型說明
call_idinteger通話 ID——在此通話的所有事件中保持一致
from_numberstringE.164 來電者號碼
to_numberstringE.164 目的地號碼(你的其中一個 ThunderPhone 號碼)

網頁小工具工作階段(web.incoming)的 data 會識別嵌入頁面,而非電話號碼:

{
  "type": "web.incoming",
  "data": {
    "call_id": 987654322,
    "origin_domain": "https://example.com",
    "publishable_key_prefix": "pk_live_a1b2"
  }
}
欄位類型說明
call_idinteger通話 ID
origin_domainstring託管小工具的頁面來源
publishable_key_prefixstring開啟工作階段的可公開金鑰前幾個字元
language, primary_languagestring當小工具工作階段要求覆寫語言時會提供
voicestring當小工具工作階段要求覆寫語音時會提供
website_contextstring當小工具傳遞每個工作階段的頁面內容時會提供

回應結構描述

傳回描述此次通話智慧體設定的 JSON 物件。 promptvoice 為必填欄位;其餘皆為選填。

{
  "prompt":  "You are a helpful booking assistant for Acme Restaurant.",
  "voice":   "john",
  "product": "spark",
  "background_track": null,
  "tools":   []
}
欄位類型必填說明
promptstring用於驅動智慧體的系統提示詞
voicestring來自 GET /v1/voices 的語音 ID,例如 johnvoice_name 可作為別名使用。未知語音將無法通過驗證並拒絕通話
productstring預設為 spark。允許值:sparkboltstorm-basestorm-base-with-ackstorm-extrastorm-extra-with-ack
thinking_levelstringminimalbase(預設)或 extra。Storm 產品會覆寫此設定:storm-extra* 強制使用 extra,其他 storm-* 強制使用 base
audio_context_modestringfull(預設)或 reduced
watchdog_enabledboolean啟用此次通話的監督功能。預設為 false
additional_audio_contextboolean | null納入通話者音訊的最近幾輪內容,而非僅納入最新一輪,以較小的延遲與成本增加改善更正,以及大量拼寫/數字資料的蒐集。預設會在來電工作階段啟用、在撥出電話停用;null 會保留預設值
storm_feedback_modestringnoneacknowledgement(預設)或 tick
languagestringprimary_language 的簡寫
primary_languagestring語言代碼,會經過正規化(預設為 en)。無法解析的代碼會拒絕通話
has_additional_languagesboolean預設為 false
additional_languagesarray of string智慧體可切換使用的其他語言
native_voice_switchingboolean預設為 false。當通話切換至其他語言時,改用該語言的原生語音(依性別配對),而非保留設定的語音
background_trackstring | null環境音訊 ID 或 null
acknowledgement_prompt_modestringauto(預設)或 manual(Storm-with-ack 產品)
acknowledgement_promptstringacknowledgement_prompt_mode="manual" 時使用
silence_interval_secondsinteger | null5–120。通話者靜默多久後進行確認,單位為秒
silence_max_checkinsinteger | null1–10
silence_checkins_enabledboolean預設為 true
connect_tone_enabledboolean預設為 false
voicemail_actionstringprompt(預設)、hangupmessage
voicemail_messagestringvoicemail_action="message" 時使用
agent_namestring回報至控制台與小工具的顯示名稱
org_namestring用於智慧體角色設定的組織顯示名稱
toolsarray內嵌函式工具結構描述(請參閱函式工具
call_idinteger選填,回傳請求中的通話 ID;會被忽略

由於 promptvoice 為必填欄位,傳回 {} 或任何 未通過驗證的回應都會以 422 拒絕通話——此路徑沒有 靜態智慧體備援(Webhook 模式中的號碼或金鑰沒有指派的智慧體)。


回應大小限制


處理常式範例

Python (FastAPI)
import hashlib
import hmac
import json
import os
 
from fastapi import FastAPI, HTTPException, Request
 
app = FastAPI()
WEBHOOK_SECRET = os.environ["THUNDERPHONE_WEBHOOK_SECRET"]
 
def verify(body: bytes, signature: str) -> bool:
    expected = hmac.new(WEBHOOK_SECRET.encode(), body, hashlib.sha256).hexdigest()
    return hmac.compare_digest(expected, signature or "")
 
@app.post("/thunderphone-webhook")
async def webhook(request: Request):
    body = await request.body()
    if not verify(body, request.headers.get("X-ThunderPhone-Signature", "")):
        raise HTTPException(status_code=401)
 
    event = json.loads(body)
    if event["type"] == "telephony.incoming":
        caller = event["data"]["from_number"]
        prompt = (
            "Greet the caller as a San Francisco local…"
            if caller.startswith("+1415")
            else "You are a friendly customer support agent…"
        )
        return {
            "prompt": prompt,
            "voice": "john",
            "product": "spark",
        }
    if event["type"] == "web.incoming":
        return {
            "prompt": "You are the website's helpful voice assistant…",
            "voice": "john",
            "product": "spark",
        }
    return {}
Node.js (Express)
import crypto from "node:crypto";
import express from "express";
 
const app = express();
const SECRET = process.env.THUNDERPHONE_WEBHOOK_SECRET;
 
function verify(body, signature) {
  const expected = crypto
    .createHmac("sha256", SECRET)
    .update(body)
    .digest("hex");
  return signature &&
    crypto.timingSafeEqual(Buffer.from(expected), Buffer.from(signature));
}
 
app.post(
  "/thunderphone-webhook",
  express.raw({ type: "application/json" }),
  (req, res) => {
    if (!verify(req.body, req.header("X-ThunderPhone-Signature"))) {
      return res.sendStatus(401);
    }
    const event = JSON.parse(req.body.toString("utf8"));
 
    if (event.type === "telephony.incoming" || event.type === "web.incoming") {
      const caller = event.data.from_number || "web";
      const prompt = caller.startsWith("+1415")
        ? "Greet the caller as a San Francisco local…"
        : "You are a friendly customer support agent…";
      return res.json({
        prompt,
        voice: "john",
        product: "spark",
      });
    }
    res.json({});
  },
);

含函式工具的回應

附加工具,讓人工智慧可在對話途中呼叫你的 API:

{
  "prompt":  "You are a booking assistant. Use the available tools to help customers schedule appointments.",
  "voice":   "john",
  "product": "spark",
  "tools": [
    {
      "type": "function",
      "function": {
        "name": "search_appointments",
        "description": "Find available appointment slots",
        "parameters": {
          "type": "object",
          "properties": {
            "date": { "type": "string", "description": "YYYY-MM-DD" },
            "service": { "type": "string" }
          },
          "required": ["date"]
        }
      },
      "endpoint": {
        "url": "https://api.example.com/appointments/search",
        "method": "POST",
        "headers": {
          "X-Api-Key": "your-key"
        }
      }
    }
  ]
}

產品方案速查表

產品延遲推理能力回應確認
spark最低基本
bolt改善
storm-base中等強大
storm-base-with-ack中等強大思考時自動填充回應
storm-extra較高深度
storm-extra-with-ack較高深度思考時自動填充回應

相關內容