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

# 통화별 동적 구성

> 웹훅의 사용자 지정 로직을 기반으로 수신 통화마다 에이전트를 선택하거나 프롬프트를 다시 작성합니다.

기본적으로 모든 전화번호와 공개 가능 키에는 정적 에이전트가
할당되어 있습니다. **발신자별** 또는 **방문자별** 맞춤 설정이
필요한 경우(VIP 라우팅, 로그인한 사용자 컨텍스트, A/B 프롬프트 테스트)에는
웹훅 모드로 전환하고 서버에서 결정하도록 하십시오.

## 작동 방식

1. [`telephony.incoming`](/ko/webhooks/events)
   (전화) 또는 [`web.incoming`](/ko/webhooks/events) (위젯)
   이벤트를 구독합니다. 두 이벤트 모두 **블로킹** 웹훅입니다. ThunderPhone은
   통화를 계속하기 전에 응답을 최대 10초 동안 기다립니다.
2. ThunderPhone이 `{call_id, from_number, to_number}`를 전송합니다(위젯
   세션은 번호 대신 위젯별 필드를 포함합니다. 자세한 내용은
   [요청 스키마](/ko/webhooks/call-incoming)를 참조하십시오).
3. 서버가 에이전트 구성(프롬프트, 음성, 제품, 도구)으로 응답합니다.
   ThunderPhone은 해당 구성을 통화에 사용합니다.
4. `{}`를 반환하거나, 시간 초과되거나, 오류가 발생하면 정적으로 할당된
   에이전트가 대체 수단으로 사용됩니다. 안전한 기본값입니다.

<Note>
  웹훅 엔드포인트 또는 레거시 단일 URL 웹훅으로 제공되는지와 관계없이,
  전화 통화(`telephony.incoming`)와 위젯 세션(`web.incoming`)에서
  동일하게 작동합니다.
</Note>

## 1. 웹훅 대상 구성

<Tabs>
  <Tab title="전화 통화">
    전화번호의 경우 엔드포인트에서 `telephony.incoming`을 구독합니다.

    ```bash theme={null}
    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`이 포함됩니다. 저장해 두십시오. 서명 검증에
    사용합니다.
  </Tab>

  <Tab title="웹 위젯">
    위젯 세션의 경우 엔드포인트 URL이 포함된 `mode="webhook"`의 공개 가능 키를
    생성합니다.

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

    위젯은 세션이 시작될 때마다 이 URL로 POST 요청을 보냅니다.
  </Tab>
</Tabs>

## 2. 핸들러 구현

세 가지 실무 원칙:

* 모든 요청에서 **서명을 검증**합니다([웹훅 서명 검증](/ko/guides/verify-webhook-signatures) 참조).
  개발 환경에서도 이를 건너뛰지 마세요. 한 번 올바르게 구현한 후 재사용합니다.
* **빠르게 응답**합니다. 10초가 절대 한도이며, 그 이후의 매초는 발신자에게 무음 시간입니다.
  필요하다면 데이터베이스를 조회하되, 다운스트림 LLM을 동기적으로 호출하지 마세요. 동적 프롬프트 생성이 필요하다면 미리 계산하고 캐시합니다.
* **깔끔하게 폴백**합니다. 예기치 않은 상태에서는 `{}`를 반환하여
  정적으로 할당된 에이전트가 통화를 처리하도록 합니다.

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

  ```javascript 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, 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
    },
  );
  ```
</CodeGroup>

## 3. 응답 스키마

응답 본문은
[수신 통화 응답 스키마](/ko/webhooks/call-incoming)와
정확히 일치합니다. 자주 사용하는 필드는 다음과 같습니다.

| 필드                            | 유형          | 설명                                                      |
| ----------------------------- | ----------- | ------------------------------------------------------- |
| `prompt`                      | 문자열(필수)     | 에이전트의 시스템 프롬프트                                          |
| `voice`                       | 문자열(필수)     | [`GET /v1/voices`](/api-reference/agents#voices)의 음성 ID |
| `product`                     | 문자열         | 기본값은 `spark`입니다                                         |
| `background_track`            | 문자열 \| null | 배경 오디오 ID                                               |
| `acknowledgement_prompt_mode` | 문자열         | `auto` 또는 `manual`(확인 응답이 있는 Storm 전용)                  |
| `acknowledgement_prompt`      | 문자열         | 모드가 `manual`일 때 필수입니다                                   |
| `tools`                       | 배열          | 인라인 함수 도구 스키마 — [함수 도구](/ko/tools/overview) 참조          |

<Note>
  통화별 발화 순서 및 `max_hold_seconds`는 웹훅 응답에서 사용할 수 없습니다.
  참조하는 [에이전트](/api-reference/agents)에서 설정하세요.
</Note>

## 패턴

### 로그인한 사용자 컨텍스트

웹훅 모드 위젯에서는 방문자의 페이지가 이미 방문자가 누구인지 알고
있습니다. 위젯 SDK가 전달하는 쿼리 문자열 매개변수
(`?customer_id=123`)와 함께 웹훅을 호출하고 서버 측에서 고객을 조회합니다.

### A/B 프롬프트 롤아웃

직접 구현하기 전에, ThunderPhone에는 변형을 정의하고, 트래픽을 분할하며, 변형별 결과를 비교하는 기본
[실험](/ko/guides/concepts) 기능
(`/dashboard/experiments` 및 에이전트 빌더의 **A/B** 탭)이 있다는 점을 참고하십시오.
웹훅은 필요하지 않습니다.

그래도 웹훅 측 제어가 필요한 경우: `call_id`를 해시하여 버킷으로 분류합니다.
`0..49`에는 프롬프트 A를 제공하고 `50..99`에는 프롬프트 B를 제공합니다. 선택한
버킷을 자체 DB에 기록한 후, 나중에 완료된 통화의 등급과 연관 분석합니다.

### 시간 기반 라우팅

업무 시간 → "실시간 지원" 에이전트, 업무 외 시간 → "메시지 남기기"
에이전트입니다. 핸들러에서 `new Date().getUTCHours()`를 기준으로 간단히 전환합니다.

***

## 다음 단계

<CardGroup cols={2}>
  <Card title="수신 통화 웹훅 레퍼런스" icon="phone" href="/ko/webhooks/call-incoming">
    모든 구성 키를 포함한 정확한 요청 및 응답 스키마입니다.
  </Card>

  <Card title="웹훅 서명 검증" icon="shield-check" href="/ko/guides/verify-webhook-signatures">
    HMAC를 한 번 정확히 구현하고 어디서나 재사용합니다.
  </Card>

  <Card title="도구 통합 구축" icon="screwdriver-wrench" href="/ko/guides/build-tool-integration">
    동적 라우팅과 에이전트별 도구를 결합합니다.
  </Card>

  <Card title="전달 시맨틱" icon="bolt" href="/ko/webhooks/overview">
    재시도, 순서, 시간 초과입니다.
  </Card>
</CardGroup>
