> ## Documentation Index
> Fetch the complete documentation index at: https://docs.thunderphone.com/llms.txt
> Use this file to discover all available pages before exploring further.

# telephony.incoming / web.incoming

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

当呼入电话到达一个**未分配智能体**的号码，或 Web 小组件会话通过处于
`mode="webhook"` 的可发布密钥启动时，ThunderPhone 会向您的
[旧版 webhook URL](/api-reference/organizations#legacy-single-url-webhook)
发送一个**阻塞式**
`telephony.incoming` / `web.incoming` 请求，并最多等待 **10 秒**以获取配置响应。使用此交互可为每通电话动态选择提示词、语音和工具——有关端到端模式，请参阅[动态通话配置指南](/zh/guides/dynamic-call-config)。

<Note>
  已订阅的 [webhook 端点](/zh/webhooks/endpoints)也会接收
  `telephony.incoming` / `web.incoming`——针对**每一通**呼入电话
  和 Web 会话，无论是否已配置智能体——但这些投递是包含 `event_id` 的即发即弃通知，绝不会阻塞。
  只有旧版单 URL webhook 承载本页面中的配置交互。端点通知的数据结构请参阅
  [事件目录](/zh/webhooks/events)。
</Note>

此阻塞式交互没有回退机制：如果您的处理程序返回非 2xx 状态、超时，或返回未通过验证的配置，
则该通话将被拒绝（电话不会接通；小组件会话请求将以 `502`/`422` 失败）。请快速响应——在您作出决定期间，来电者会听到回铃音。

## 请求载荷

对于电话呼叫（`telephony.incoming`）：

```json theme={null}
{
  "type": "telephony.incoming",
  "data": {
    "call_id":     987654321,
    "from_number": "+14155550199",
    "to_number":   "+15551234567"
  }
}
```

| 字段            | 类型      | 描述                               |
| ------------- | ------- | -------------------------------- |
| `call_id`     | integer | 通话 ID——在该通话的所有事件中保持不变            |
| `from_number` | string  | E.164 来电号码                       |
| `to_number`   | string  | E.164 目标号码（您的 ThunderPhone 号码之一） |

对于 Web 小组件会话（`web.incoming`），`data` 标识嵌入页面而非电话号码：

```json theme={null}
{
  "type": "web.incoming",
  "data": {
    "call_id": 987654322,
    "origin_domain": "https://example.com",
    "publishable_key_prefix": "pk_live_a1b2"
  }
}
```

| 字段                             | 类型      | 描述                |
| ------------------------------ | ------- | ----------------- |
| `call_id`                      | integer | 通话 ID             |
| `origin_domain`                | string  | 托管小组件的页面源         |
| `publishable_key_prefix`       | string  | 打开该会话的可发布密钥的前几个字符 |
| `language`, `primary_language` | string  | 小组件会话请求语言覆盖时存在    |
| `voice`                        | string  | 小组件会话请求语音覆盖时存在    |
| `website_context`              | string  | 小组件传入每会话页面上下文时存在  |

<Note>
  Webhook 模式的小组件会在设置了可发布密钥自身的
  `webhook_url` 时将此请求发送至该 URL，否则回退至组织级
  webhook URL。无论哪种方式，都会使用组织 webhook 的 `secret` 进行签名。
</Note>

***

## 响应架构

返回一个 JSON 对象，用于描述本次通话的智能体配置。
必须提供 `prompt` 和 `voice`；其他字段均为可选。

```json theme={null}
{
  "prompt":  "You are a helpful booking assistant for Acme Restaurant.",
  "voice":   "john",
  "product": "spark",
  "background_track": null,
  "tools":   []
}
```

| 字段                            | 类型              | 必填 | 描述                                                                                                          |
| ----------------------------- | --------------- | -- | ----------------------------------------------------------------------------------------------------------- |
| `prompt`                      | string          | 是  | 驱动智能体的系统提示词                                                                                                 |
| `voice`                       | string          | 是  | 来自 [`GET /v1/voices`](/api-reference/agents#voices) 的语音 ID，例如 `john`。`voice_name` 可作为别名使用。未知语音将无法通过验证，并拒绝通话 |
| `product`                     | string          | 否  | 默认为 `spark`。允许值：`spark`、`bolt`、`storm-base`、`storm-base-with-ack`、`storm-extra`、`storm-extra-with-ack`      |
| `thinking_level`              | string          | 否  | `minimal`、`base`（默认）或 `extra`。Storm 产品会覆盖此设置：`storm-extra*` 强制使用 `extra`，其他 `storm-*` 强制使用 `base`           |
| `audio_context_mode`          | string          | 否  | `full`（默认）或 `reduced`                                                                                       |
| `watchdog_enabled`            | boolean         | 否  | 为本次通话启用监管。默认为 `false`                                                                                       |
| `storm_feedback_mode`         | string          | 否  | `none`、`acknowledgement`（默认）或 `tick`                                                                        |
| `language`                    | string          | 否  | `primary_language` 的简写                                                                                      |
| `primary_language`            | string          | 否  | 语言代码，会被标准化处理（默认 `en`）。无法解析的代码将拒绝通话                                                                          |
| `has_additional_languages`    | boolean         | 否  | 默认为 `false`                                                                                                 |
| `additional_languages`        | array of string | 否  | 智能体可切换使用的额外语言                                                                                               |
| `background_track`            | string \| null  | 否  | 环境音频 ID 或 `null`                                                                                            |
| `acknowledgement_prompt_mode` | string          | 否  | `auto`（默认）或 `manual`（Storm-with-ack 产品）                                                                     |
| `acknowledgement_prompt`      | string          | 否  | 当 `acknowledgement_prompt_mode="manual"` 时使用                                                                |
| `silence_interval_seconds`    | integer \| null | 否  | 5–120。呼叫者静默多久后进行确认，以秒为单位                                                                                    |
| `silence_max_checkins`        | integer \| null | 否  | 1–10                                                                                                        |
| `silence_checkins_enabled`    | boolean         | 否  | 默认为 `true`                                                                                                  |
| `connect_tone_enabled`        | boolean         | 否  | 默认为 `false`                                                                                                 |
| `voicemail_action`            | string          | 否  | `prompt`（默认）、`hangup` 或 `message`                                                                           |
| `voicemail_message`           | string          | 否  | 当 `voicemail_action="message"` 时使用                                                                          |
| `agent_name`                  | string          | 否  | 报告至控制台和小组件的显示名称                                                                                             |
| `org_name`                    | string          | 否  | 用于智能体角色设定的组织显示名称                                                                                            |
| `tools`                       | array           | 否  | 内联函数工具架构（请参阅[函数工具](/zh/tools/overview)）                                                                     |
| `call_id`                     | integer         | 否  | 可选地回显请求的通话 ID；将被忽略                                                                                          |

<Note>
  未知的顶级键会被静默**忽略**——拼写错误的字段
  名称不会导致配置被拒绝，只是不会生效。此处不接受发言顺序
  和 `max_hold_seconds`；它们只能在[智能体](/api-reference/agents)本身上
  配置。
</Note>

由于 `prompt` 和 `voice` 为必填项，返回 `{}` 或任何
未通过验证的响应都会以 `422` 拒绝通话——此路径不提供
静态智能体回退机制（Webhook 模式下的号码或密钥没有分配的智能体）。

***

## 示例处理程序

<CodeGroup>
  ```python Python (FastAPI) theme={null}
  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 {}
  ```

  ```javascript Node.js (Express) theme={null}
  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({});
    },
  );
  ```
</CodeGroup>

***

## 使用函数工具响应

附加工具，使 AI 能够在对话过程中调用您的 API：

```json theme={null}
{
  "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"
        }
      }
    }
  ]
}
```

<Tip>
  工具端点请求使用与签署此次交换的<strong>同一组织 Webhook 密钥</strong>进行签名。有关确切结构和已签名请求格式，请参阅
  [函数工具](/zh/tools/overview)。
</Tip>

***

## 产品层级速查表

| 产品                     | 延迟 | 推理能力 | 确认      |
| ---------------------- | -- | ---- | ------- |
| `spark`                | 最低 | 基础   | —       |
| `bolt`                 | 低  | 增强   | —       |
| `storm-base`           | 中等 | 强    | —       |
| `storm-base-with-ack`  | 中等 | 强    | 思考时自动填充 |
| `storm-extra`          | 较高 | 深度   | —       |
| `storm-extra-with-ack` | 较高 | 深度   | 思考时自动填充 |

***

## 相关内容

<CardGroup cols={2}>
  <Card title="telephony.complete / web.complete" icon="phone-slash" href="/zh/webhooks/call-complete">
    非阻塞式通话结束事件。
  </Card>

  <Card title="函数工具" icon="screwdriver-wrench" href="/zh/tools/overview">
    `tools[]` 的完整 JSON 架构和签名端点约定。
  </Card>

  <Card title="Webhook 端点" icon="bolt" href="/zh/webhooks/endpoints">
    为 `telephony.incoming` / `web.incoming` 订阅多个 URL。
  </Card>

  <Card title="动态通话配置" icon="wand-magic-sparkles" href="/zh/guides/dynamic-call-config">
    按来电者配置提示词、工具和 A/B 测试的模式。
  </Card>
</CardGroup>
