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

Webhooks

telephony.incoming / web.incoming

用于实时配置入站通话的阻塞式 Webhook。

当呼入电话到达一个未分配智能体的号码,或 Web 小组件会话通过处于 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 小组件会话(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({});
  },
);

包含函数工具的响应

附加工具,以便 AI 可在对话过程中调用您的 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较高深度思考时自动填充

相关内容