> ## 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.

# 端對端測試智慧體（API）

> 透過 ThunderPhone API 執行單次模擬、平行場景批次與發行閘門測試套件，讓智慧體退化問題在客戶聽見之前就被捕捉。

<Note>
  偏好使用控制台？相同功能位於 **模擬**
  （`/dashboard/simulations`），其中包括人工智慧情境生成——請參閱
  [模擬通話](/zh-Hant/guides/simulate-a-call)。本頁說明程式化使用方式。
</Note>

反覆改善人工智慧語音智慧體，意味著反覆調整其提示、工具，
以及處理邊界情況的方式。**模擬 API** 會使用你提供的情境提示，
對智慧體執行真實通話。以智慧體為目標會建立機器人對機器人的執行；
以電話號碼為目標則會建立 SIP 迴路執行。每次執行都會產生包含
逐字稿、評分與計費的真實通話紀錄，因此你能確切了解智慧體的
行為與成本。

適用於：

* 每次編輯提示後，在部署前執行冒煙測試
* 串接至 CI 的迴歸測試套件（掛接 `test-call.completed` webhook
  → 若分數下降則使建置失敗）
* 壓力測試並行數限制

## 單次執行：單一測試

```bash theme={null}
curl -X POST https://api.thunderphone.com/v1/simulations \
  -H "Authorization: Bearer sk_live_YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "target_type":     "agent",
    "target_id":       12,
    "direction":       "outbound",
    "scenario_prompt": "You are a polite caller asking about refund policy for order 12345.",
    "consent_to_charge": true
  }'
```

欄位：

| 欄位                              | 類型  | 必填    | 說明                                              |
| ------------------------------- | --- | ----- | ----------------------------------------------- |
| `target_type`                   | 字串  | 是     | `agent` 或 `phone_number`                        |
| `target_id`                     | 整數  | 是     | 智慧體 ID（或電話號碼 ID）                                |
| `direction`                     | 字串  | 否     | `outbound`（預設；測試來電者撥打）或 `inbound`（測試來電者接聽）      |
| `scenario_prompt`               | 字串  | 否     | 決定測試機器人要說的內容                                    |
| `language` / `primary_language` | 字串  | 否     | 測試來電者使用的語言；不支援的代碼會遭拒絕                           |
| `simulator_product`             | 字串  | 否     | `testing`（預設），或使用 `spark` 以模擬更像真人的來電者，例如暖轉接諮詢測試 |
| `consent_to_charge`             | 布林值 | **是** | 必須為 `true`。費用估算會計入所選智慧體和模擬來電者，以及任何電話線路          |
| `target_number`                 | 字串  | 否     | 遠端一側的 E.164 覆寫值；否則使用平台測試號碼                      |

`mode` 為唯讀，並由 `target_type` 衍生：`agent` 會產生
`mode="bot"`，而 `phone_number` 會產生 `mode="sip"`。

回應為 `status="queued"` 的[模擬執行物件](/api-reference/test-calls#test-call-run-object)。
輪詢直到 `status` 變為 `completed` 或 `failed`；設定 `call_id` 後，
透過 [`GET /v1/calls/{call_id}/transcript`](/api-reference/calls#get-transcript)
載入逐字稿。

## 批次：平行情境

同時執行 N 個情境——適合讓迴歸測試套件平行測試每個已知的
邊界情況：

```bash theme={null}
curl -X POST https://api.thunderphone.com/v1/simulations/batches \
  -H "Authorization: Bearer sk_live_YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "target_type":     "agent",
    "target_id":       12,
    "direction":       "outbound",
    "run_count":       5,
    "stagger_seconds": 2,
    "scenario_prompts": [
      "Ask about refund policy.",
      "Ask for hours of operation.",
      "Complain about a delayed shipment.",
      "Ask to speak with a human.",
      "Ask an unrelated trivia question."
    ],
    "consent_to_charge": true
  }'
```

回應包含子執行 ID 的 `run_ids` 清單。取得批次狀態：

```bash theme={null}
curl https://api.thunderphone.com/v1/simulations/batches/{batch_id} \
  -H "Authorization: Bearer sk_live_YOUR_API_KEY"
```

`run_count` 上限為 20；`stagger_seconds` 會間隔啟動時間，
以避免對智慧體造成過大負載（0–60 秒）。

## 將其串接至 CI

在 **模擬** 頁面
（`/dashboard/simulations`）建立發行閘門套件——選擇智慧體、手動新增情境，或
點選 **使用 AI 產生情境**，根據智慧體的提示詞草擬情境
（可選擇額外進行邊緣案例檢查），再將它們分組為套件。
套件會固定其情境與智慧體，以及最低通過率和可選的零關鍵失敗規則。通過的執行結果會成為已接受的基準；後續從通過→失敗的變化會回傳為迴歸問題。

在 CI 中使用[組織 API 金鑰](/api-reference/developer-api-keys)。
此指令碼會觸發套件、輪詢直到評分與比較完成，並在判定結果不是 `pass` 時以非零狀態碼結束：

```bash theme={null}
#!/usr/bin/env bash
set -euo pipefail

: "${THUNDERPHONE_API_KEY:?Set THUNDERPHONE_API_KEY}"
: "${THUNDERPHONE_ORG_ID:?Set THUNDERPHONE_ORG_ID}"
: "${THUNDERPHONE_SUITE_ID:?Set THUNDERPHONE_SUITE_ID}"

base="https://api.thunderphone.com/v1/orgs/${THUNDERPHONE_ORG_ID}/suites/${THUNDERPHONE_SUITE_ID}"
auth="Authorization: Bearer ${THUNDERPHONE_API_KEY}"

run_id="$(curl --fail --silent --show-error -X POST "${base}/run" \
  -H "$auth" -H "Content-Type: application/json" -d '{}' | jq -r '.id')"

deadline=$((SECONDS + 1800))
while (( SECONDS < deadline )); do
  result="$(curl --fail --silent --show-error \
    "${base}/runs/${run_id}" -H "$auth")"
  status="$(jq -r '.status' <<<"$result")"
  if [[ "$status" == "completed" ]]; then
    jq . <<<"$result"
    [[ "$(jq -r '.verdict' <<<"$result")" == "pass" ]]
    exit
  fi
  sleep 10
done

echo "ThunderPhone suite timed out" >&2
exit 1
```

`POST /v1/orgs/{org_id}/suites/{suite_id}/run` 會以執行 ID 回傳 `202`。
`GET /v1/orgs/{org_id}/suites/{suite_id}/runs/{run_id}` 會回傳
`status`、`verdict`、`pass_rate`、`critical_failure_count`，以及基準的
`regressions` 清單。兩個端點都會將 URL 中的組織綁定至 API 金鑰所屬的組織。

## 模式

### 每個提示詞的迴歸測試語料庫

維護一個包含 `{name, scenario_prompt, expected_outcome}`
元組的 JSON 檔案。每次提示詞變更時，將完整集合以批次方式執行；並將通話記錄與評分和前一次執行結果進行差異比較。

### 每次發行的冒煙測試

每次部署後執行一批包含五個正常路徑情境的測試。此測試對延遲敏感，因此請保持 `stagger_seconds: 0`。

### 延遲效能評測

針對不同產品層級（`spark`、
`bolt`、`storm-base`）執行相同情境。比較 `call.graded` 分數，以及每筆產生的通話紀錄中的 `duration_seconds`。

***

## 後續步驟

<CardGroup cols={2}>
  <Card title="測試通話參考資料" icon="flask" href="/api-reference/test-calls">
    所有查詢參數、狀態碼與批次格式。
  </Card>

  <Card title="AI 評分" icon="chart-line" href="/api-reference/calls#ai-call-grading">
    自動為每次測試執行評分，以長期追蹤品質。
  </Card>

  <Card title="問題報告" icon="triangle-exclamation" href="/api-reference/issue-reports">
    標記特定測試以供人工審查。
  </Card>

  <Card title="test-call.completed Webhook" icon="bolt" href="/zh-Hant/webhooks/events">
    將結果串流至你的 CI / Slack / PagerDuty。
  </Card>
</CardGroup>
