Open in
Dynamic per-call configuration
Pick the answering agent — or rewrite its prompt and settings — separately for every incoming call, driven by custom logic in a webhook you control.
By default every phone number and publishable key has a static agent assigned. When you need per-caller or per-visitor customization — VIP routing, logged-in user context, A/B prompt tests — switch to webhook-mode and let your server decide.
How it works
- You subscribe to the
telephony.incoming(phone) orweb.incoming(widget) event. Both are blocking webhooks: ThunderPhone waits for your response before continuing the call, up to 13 seconds for a phone call (one retry included) and 10 seconds for a widget session. - ThunderPhone sends you
{call_id, from_number, to_number}(widget sessions carry widget-specific fields instead of numbers — see the request schema). - Your server responds with an agent configuration (prompt, voice, product, tools, words, and other supported call settings). ThunderPhone uses that configuration for the call.
- There is no fallback agent. If you return
{}or an invalid configuration, or the request still fails after its retry, the phone call is ended right away and recorded withend_reasoninbound_config_webhook_failed; a widget session request fails.
1. Configure the webhook destination
For phone numbers, subscribe your endpoint to telephony.incoming:
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"]
}'The response includes a one-shot secret — save it; you'll use it
for signature verification.
For widget sessions, create a publishable key in mode="webhook"
with your endpoint URL baked in:
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"]
}'The widget will POST to this URL on every session start.
2. Implement the handler
Three rules of thumb:
- Verify the signature on every request (see Verify webhook signatures). Don't skip this in dev — get it right once and reuse.
- Respond fast. A phone call's first attempt is cut off at 10 seconds and the whole exchange at 13, and every second is dead air for the caller. Do database lookups if you need to, but don't call downstream LLMs synchronously — if you want dynamic prompt generation, pre-compute and cache.
- Fall back cleanly. For any unexpected state, answer with a
default
promptandvoice(or a savedagent_id). Returning{}or an error status ends the call.
import hashlib
import hmac
import json
import os
from fastapi import FastAPI, HTTPException, Request
app = FastAPI()
SECRET = os.environ["THUNDERPHONE_WEBHOOK_SECRET"]
DEFAULT_AGENT_ID = int(os.environ["THUNDERPHONE_DEFAULT_AGENT_ID"])
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 {}
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": "bolt",
}
# Everyone else gets your usual saved agent ({} would end the call).
return {"agent_id": DEFAULT_AGENT_ID}
def lookup_customer(phone: str):
# ... your CRM integration ...
passimport crypto from "node:crypto";
import express from "express";
const app = express();
const SECRET = process.env.THUNDERPHONE_WEBHOOK_SECRET;
const DEFAULT_AGENT_ID = Number(process.env.THUNDERPHONE_DEFAULT_AGENT_ID);
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: "bolt",
});
}
// Everyone else gets your usual saved agent ({} would end the call).
res.json({ agent_id: DEFAULT_AGENT_ID });
},
);3. Response schema
The response body matches the incoming-call response schema exactly. The commonly-used fields:
| Field | Type | Description |
|---|---|---|
prompt | string (required) | System prompt for the agent |
voice | string (required) | Voice id from GET /v1/voices |
product | string | Send bolt. Defaults to spark, an older value that is still accepted. |
background_track | string | null | Ambient audio id |
acknowledgement_prompt_mode | string | auto or manual (older -with-ack product values only) |
acknowledgement_prompt | string | Required when mode is manual |
language_switching | string | For multilingual agents, ask_first or follow_caller |
speech_detection | string | standard or enhanced |
voice_speed | number | How fast the agent talks, 0.8 to 1.3; 1.0 is the normal pace |
tools | array | Inline function-tool schemas — see Function Tools |
Keep a saved agent and supply variables or context
Return {"agent_id": 12, "variables": {"name": "Ada"}} to use that organization's
saved agent with per-call data. Its prompt can contain {{name}} or
{{name|Friend}}. Webhook variables merge over request-level variables; null
uses the placeholder default, or empty text if none is provided. The final
values and unresolved names appear in call details and completion webhooks.
Add context, a free-form string of up to 20,000 characters, to give the agent
a brief for this call (notes from your CRM, the reason you expect the call);
it is added after the prompt in a delimited block.
Saved-agent responses accept only agent_id, variables, context, timezone, language and
overrides. If prompt is
present, the response uses inline configuration and ignores agent_id; the inline prompt must still be valid. Inline responses can also set speech_detection to standard or enhanced, and voice_speed from 0.8 to 1.3. If your webhook is the assigned agent's own call setup webhook, you can also omit agent_id and return just variables, context, timezone, language or overrides to keep that assigned agent (including any version pin) for the call. Inline
configuration responses may also include variables and context. Saved-agent responses use
the agent's deployed A/B split on both phone and widget calls, then render variables. See call variables
for limits and session API support. Blocking configuration comes from the legacy
phone-number/organization URL or a webhook-mode widget key; endpoint-system
incoming events are notifications only.
Set the time zone per call
One agent can answer for contacts in different time zones. Add timezone, an
IANA name, to a saved-agent or inline response and the agent states the date
and time and offers times in that zone for this call, ahead of the agent's own
time zone:
{"agent_id": 12, "timezone": "America/Chicago", "variables": {"name": "Ada"}}Send the zone rather than a timestamp in variables: the agent's clock keeps
running during the call, and a time you pass in goes stale. A value that is not
an IANA zone is ignored and the call connects in the agent's zone.
Set the language per call
One agent can answer in each of its languages. Add language, a supported
language code such as es (es-MX is read as es), next to agent_id and the
call starts in that language:
{"agent_id": 12, "language": "es", "variables": {"name": "Ada"}}The agent speaks it with its voice for that language: its
language_voices entry; else, with
native_voice_switching on, the native voice the agent would switch to for
that language; else its own voice, when that voice speaks the language. On
unrecorded calls, ThunderPhone also plays the live-processing notice in the
call's language. Then the agent's other languages and its primary language stay
available for switching. If none of these can speak it, the call still starts in that
language, with the language's default voice (an agent with a custom voice keeps
it) and no other languages. If the call later switches mid-call to another of
the agent's languages, it also uses that language's language_voices entry
when both voices are catalog voices; otherwise the usual switching rules apply.
Full duplex agents are different: in any supported language, the call keeps the
agent's own voice, and language_voices and native voice switching do not
apply. Only a code that is not a supported language is rejected. Widget and
realtime sessions take the same language field.
Change the agent's settings per call
When your response names a saved agent with agent_id, you can add an overrides object to change some of that agent's settings for this call only. ThunderPhone keeps using the saved agent, including any version pin, and does not change the agent itself.
Use overrides for call behavior such as the agent's prompt, voice, language behavior, turn-taking, voicemail and silence handling, limits, and built-in tool settings that apply during the live call. Do not send those settings beside agent_id; put them inside overrides.
Use the separate top-level fields for per-call language and timezone, not overrides.
Example:
{
"agent_id": 12,
"overrides": {
"voice": "john"
}
}Change the agent's settings per call
One saved agent can serve many callers who each need something a little
different: their own voice, a slower pace, a longer silence before a
check-in. Add overrides next to agent_id and the call runs the agent with
those settings changed. The saved agent itself is not changed, and the
override applies to that call only.
{"agent_id": 12, "overrides": {"voice": "john", "voice_speed": 1.1}}The same overrides object works on
POST /v1/call,
POST /v1/realtime/sessions
(over the WebSocket, as session.config.overrides in the session.update that starts the agent), and in a webhook answer,
including an agent's own call setup webhook answer, where it can stand
without agent_id.
Keys are the setting names the Agents API uses, and
each value is checked the same way an edit of the agent would check it. A
value the agent would refuse, or a setting that is not on the list below,
refuses the call: POST /v1/call and realtime sessions return 400 with the
reason under overrides, a webhook-configured phone call ends with
config_webhook_failure.reason invalid_overrides, with the refused
settings in fields, and a webhook-mode widget session fails with 400
config_error. A retired product value runs as bolt where the agent's
own would. A voice is checked against the agent's own languages, as on the
agent; with a per-call language, the override voice speaks it when it can,
and otherwise a voice that can is chosen. On a realtime session, an
organization set up for its own Cartesia voices
can also override voice with cartesia:<voice id>; phone calls and webhook
answers do not accept that form.
| Kind | Settings you can override |
|---|---|
| What the agent says and how it sounds | prompt, voice, voice_speed, background_track, words |
| Other languages | additional_languages, native_voice_switching, language_voices, language_switching |
| Hearing, thinking and turn-taking | product, speech_detection, audio_tier, endpointing, intelligence, faster_replies_enabled, thinking_level, audio_context_mode, additional_audio_context, watchdog_enabled |
| Who speaks first and what fills pauses | inbound_speak_order, outbound_speak_order, acknowledgement_prompt_mode, acknowledgement_prompt, acknowledgement_feedback_mode, connect_tone_enabled, typing_sounds_enabled, typing_sound, filler_phrases_enabled, tool_start_line |
| Voicemail and silence | voicemail_action, voicemail_message, silence_interval_seconds, silence_max_checkins, silence_checkins_enabled, silence_hangup_seconds, silence_final_action, silence_transfer_destination, silence_final_message |
| Limits | max_call_duration_seconds, ring_duration_seconds, max_hold_seconds |
| Built-in tools | send_email_enabled, send_sms_enabled, calculator_enabled, play_sound_asset, warm_transfer_style, warm_transfer_briefing, system_tool_settings |
Some settings stay with the saved agent:
- The call's language and time zone have their own per-call fields,
languageandtimezone, soprimary_languageandtimezoneare not overrides. - Recording, the consent announcement and other disclosures, PHI handling
and do-not-call detection always follow the saved agent. A call can still
ask to be handled as PHI with
phi_modewhere that field is offered. - The agent's tools, knowledge, steps, transfer directory, SMS sender and call setup webhook stay as saved. So do who it may email or text: a call can turn the email and text tools on or off, but they reach only the agent's own recipients.
- What happens after the call (summaries, reports, extracted fields) follows the saved agent.
A setting that does nothing on a given kind of call still does nothing when overridden: realtime sessions, for example, never run silence check-ins.
A call that overrides a price setting (product, intelligence,
audio_tier or endpointing) is billed at the current price for what it ran.
An agent's kept price does not apply to that call, just as it would end if you
deployed the same change. A voice override keeps the kept price and adds that
voice's own fee, if it has one. When the agent is in a split test, the call still takes an
arm, and an override wins over the arm for the settings both change. The
call object's agent_overrides shows what each call
changed.
Patterns
Logged-in user context
In webhook-mode widgets, the visitor's page already knows who they
are. Call your webhook with a query string parameter the widget SDK
forwards (?customer_id=123) and look up the customer server-side.
A/B prompt rollout
Before you hand-roll this, note that ThunderPhone has a native
Experiments feature
(an agent's History & trials in the app, or /dashboard/experiments in
the old view) that
defines variants, splits traffic, and compares outcomes per variant —
no webhook required.
If you need webhook-side control anyway: hash call_id → bucket;
serve prompt A for 0..49 and prompt B for 50..99. Record which
bucket you chose in your own DB and later correlate against the
completed call's grade.
Time-based routing
Business hours → "live support" agent; after-hours → "take a message"
agent. Pure switch on new Date().getUTCHours() in your handler.