telnyx-ai-outbound-voice-python

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Telnyx AI Outbound Voice Calls - Python

Telnyx AI外呼语音通话 - Python

Make an AI assistant call any phone number. This skill covers the complete setup from purchasing a number to triggering the call.
让AI助手拨打任意电话号码。本skill涵盖从购买号码到触发通话的完整配置流程。

Installation

安装

bash
pip install telnyx requests
bash
pip install telnyx requests

Setup

配置

python
import os
from telnyx import Telnyx

client = Telnyx(api_key=os.environ.get("TELNYX_API_KEY"))
python
import os
from telnyx import Telnyx

client = Telnyx(api_key=os.environ.get("TELNYX_API_KEY"))

Prerequisites

前置条件

Outbound voice calls require all of the following. Missing any one produces a specific error — see Troubleshooting.
  1. A purchased Telnyx phone number
  2. A TeXML application
  3. The phone number assigned to the TeXML application
  4. An outbound voice profile with destination countries whitelisted
  5. An AI assistant with
    telephony_settings.default_texml_app_id
    set to the TeXML app
外呼语音通话需要满足所有以下条件,缺少任意一项都会返回对应的错误——参见问题排查
  1. 已购买的Telnyx电话号码
  2. 一个TeXML应用
  3. 电话号码已绑定到TeXML应用
  4. 已配置目标国家白名单的外呼语音配置文件
  5. AI助手的
    telephony_settings.default_texml_app_id
    已设置为对应TeXML应用ID

Model availability

模型可用性

Model availability varies by account. If
client.ai.assistants.create()
returns 422 "not available for inference", discover working models from existing assistants:
python
for a in client.ai.assistants.list().data:
    print(a.model)
Commonly available:
openai/gpt-4o
,
Qwen/Qwen3-235B-A22B
.
模型可用性因账户而异。如果
client.ai.assistants.create()
返回422错误「not available for inference」,可以从现有助手列表中查询可用模型:
python
for a in client.ai.assistants.list().data:
    print(a.model)
常见可用模型:
openai/gpt-4o
Qwen/Qwen3-235B-A22B

Step 1: Purchase a phone number

步骤1:购买电话号码

python
import time

available = client.available_phone_numbers.list()
phone = available.data[0].phone_number

number_order = client.number_orders.create(
    phone_numbers=[{"phone_number": phone}],
)
time.sleep(3)

order = client.number_orders.retrieve(number_order.data.id)
assert order.data.status == "success"
print(f"Purchased: {phone}")
python
import time

available = client.available_phone_numbers.list()
phone = available.data[0].phone_number

number_order = client.number_orders.create(
    phone_numbers=[{"phone_number": phone}],
)
time.sleep(3)

order = client.number_orders.retrieve(number_order.data.id)
assert order.data.status == "success"
print(f"购买成功:{phone}")

Step 2: Create a TeXML application

步骤2:创建TeXML应用

The
voice_url
is required by the API but is not used for outbound AI assistant calls. The TeXML app ID is also used as the
connection_id
when assigning phone numbers.
python
texml_app = client.texml_applications.create(
    friendly_name="My AI Assistant App",
    voice_url="https://example.com/placeholder",
)
app_id = texml_app.data.id  # This is also the connection_id for phone number assignment
API要求传入
voice_url
参数,但AI助手外呼场景不会使用该地址。TeXML应用ID同时也会作为绑定电话号码时使用的
connection_id
python
texml_app = client.texml_applications.create(
    friendly_name="My AI Assistant App",
    voice_url="https://example.com/placeholder",
)
app_id = texml_app.data.id  # 该ID同时也是绑定电话号码时使用的connection_id

Step 3: Assign the phone number to the TeXML application

步骤3:将电话号码绑定到TeXML应用

A phone number cannot make calls until it is assigned to a connection.
python
import requests

requests.patch(
    f"https://api.telnyx.com/v2/phone_numbers/{phone}",
    headers={
        "Authorization": f"Bearer {os.environ['TELNYX_API_KEY']}",
        "Content-Type": "application/json",
    },
    json={"connection_id": app_id},
)
电话号码只有绑定到连接后才能发起通话。
python
import requests

requests.patch(
    f"https://api.telnyx.com/v2/phone_numbers/{phone}",
    headers={
        "Authorization": f"Bearer {os.environ['TELNYX_API_KEY']}",
        "Content-Type": "application/json",
    },
    json={"connection_id": app_id},
)

Step 4: Whitelist destination countries

步骤4:配置目标国家白名单

By default only US and CA are whitelisted. Calling any other country without whitelisting it first returns 403 error code D13.
python
import requests

headers = {
    "Authorization": f"Bearer {os.environ['TELNYX_API_KEY']}",
    "Content-Type": "application/json",
}
默认仅美国和加拿大在白名单中。如果未提前添加白名单就拨打其他国家的号码,会返回403错误码D13。
python
import requests

headers = {
    "Authorization": f"Bearer {os.environ['TELNYX_API_KEY']}",
    "Content-Type": "application/json",
}

Find the outbound voice profile

查找外呼语音配置文件

r = requests.get( "https://api.telnyx.com/v2/outbound_voice_profiles", headers=headers ) ovp_id = r.json()["data"][0]["id"]
r = requests.get( "https://api.telnyx.com/v2/outbound_voice_profiles", headers=headers ) ovp_id = r.json()["data"][0]["id"]

Add destination countries (ISO 3166-1 alpha-2 codes)

添加目标国家(ISO 3166-1 alpha-2编码)

requests.patch( f"https://api.telnyx.com/v2/outbound_voice_profiles/{ovp_id}", headers=headers, json={"whitelisted_destinations": ["US", "CA", "IE", "GB"]}, )
requests.patch( f"https://api.telnyx.com/v2/outbound_voice_profiles/{ovp_id}", headers=headers, json={"whitelisted_destinations": ["US", "CA", "IE", "GB"]}, )

Assign the profile to the TeXML app

将配置文件绑定到TeXML应用

requests.patch( f"https://api.telnyx.com/v2/texml_applications/{app_id}", headers=headers, json={ "friendly_name": "My AI Assistant App", "voice_url": "https://example.com/placeholder", "outbound": {"outbound_voice_profile_id": ovp_id}, }, )
undefined
requests.patch( f"https://api.telnyx.com/v2/texml_applications/{app_id}", headers=headers, json={ "friendly_name": "My AI Assistant App", "voice_url": "https://example.com/placeholder", "outbound": {"outbound_voice_profile_id": ovp_id}, }, )
undefined

Step 5: Create the AI assistant with telephony settings

步骤5:创建带电话配置的AI助手

telephony_settings
with
default_texml_app_id
is required for outbound calls. Without it,
scheduled_events.create()
returns 400 "Assistant does not have telephony settings configured".
python
assistant = client.ai.assistants.create(
    name="My Voice Assistant",
    model="openai/gpt-4o",
    instructions=(
        "You are a helpful phone assistant. "
        "Keep your answers concise and conversational since this is a phone call."
    ),
    greeting="Hello! How can I help you today?",
    telephony_settings={"default_texml_app_id": app_id},
)
To add telephony to an existing assistant:
python
client.ai.assistants.update(
    assistant_id="your-assistant-id",
    telephony_settings={"default_texml_app_id": app_id},
)
外呼功能必须配置包含
default_texml_app_id
telephony_settings
。缺少该配置时,
scheduled_events.create()
会返回400错误「Assistant does not have telephony settings configured」。
python
assistant = client.ai.assistants.create(
    name="My Voice Assistant",
    model="openai/gpt-4o",
    instructions=(
        "你是一位贴心的电话助手。" 
        "由于是通话场景,请保持回答简洁口语化。"
    ),
    greeting="您好!请问有什么可以帮您的?",
    telephony_settings={"default_texml_app_id": app_id},
)
为现有助手添加电话配置:
python
client.ai.assistants.update(
    assistant_id="your-assistant-id",
    telephony_settings={"default_texml_app_id": app_id},
)

Step 6: Trigger an outbound call

步骤6:触发外呼

Use
scheduled_events.create()
with a time a few seconds in the future for an immediate call.
python
from datetime import datetime, timezone, timedelta

event = client.ai.assistants.scheduled_events.create(
    assistant_id=assistant.id,
    telnyx_conversation_channel="phone_call",
    telnyx_end_user_target="+13125550001",  # Number to call (recipient)
    telnyx_agent_target=phone,               # Your Telnyx number (caller ID)
    scheduled_at_fixed_datetime=(
        datetime.now(timezone.utc) + timedelta(seconds=5)
    ).isoformat(),
)
print(f"Status: {event.status}")  # "pending"
ParameterTypeRequiredDescription
assistant_id
string (UUID)YesThe AI assistant that handles the call.
telnyx_conversation_channel
stringYesMust be
"phone_call"
.
telnyx_end_user_target
string (E.164)YesPhone number to call (recipient).
telnyx_agent_target
string (E.164)YesYour Telnyx number (caller ID). Must be assigned to the TeXML app.
scheduled_at_fixed_datetime
string (ISO 8601)YesWhen to place the call. ~5s in the future for immediate.
dynamic_variables
objectNoVariables to pass to the assistant.
conversation_metadata
objectNoMetadata to attach to the conversation.
如需立即发起通话,可以将
scheduled_events.create()
的时间设置为未来几秒后。
python
from datetime import datetime, timezone, timedelta

event = client.ai.assistants.scheduled_events.create(
    assistant_id=assistant.id,
    telnyx_conversation_channel="phone_call",
    telnyx_end_user_target="+13125550001",  # 被叫号码(接收方)
    telnyx_agent_target=phone,               # 你的Telnyx号码(主叫ID)
    scheduled_at_fixed_datetime=(
        datetime.now(timezone.utc) + timedelta(seconds=5)
    ).isoformat(),
)
print(f"状态:{event.status}")  # "pending"
参数类型是否必填描述
assistant_id
string (UUID)处理通话的AI助手ID。
telnyx_conversation_channel
string必须为
"phone_call"
telnyx_end_user_target
string (E.164)被叫号码(接收方)。
telnyx_agent_target
string (E.164)你的Telnyx号码(主叫ID),必须已绑定到TeXML应用。
scheduled_at_fixed_datetime
string (ISO 8601)发起通话的时间,如需立即拨打可设置为未来约5秒。
dynamic_variables
object传递给助手的变量。
conversation_metadata
object挂载到会话的元数据。

Complete minimal example

完整最小示例

python
import os, time
from datetime import datetime, timezone, timedelta
from telnyx import Telnyx
import requests

api_key = os.environ["TELNYX_API_KEY"]
client = Telnyx(api_key=api_key)
headers = {"Authorization": f"Bearer {api_key}", "Content-Type": "application/json"}
python
import os, time
from datetime import datetime, timezone, timedelta
from telnyx import Telnyx
import requests

api_key = os.environ["TELNYX_API_KEY"]
client = Telnyx(api_key=api_key)
headers = {"Authorization": f"Bearer {api_key}", "Content-Type": "application/json"}

1. Buy a number

1. 购买号码

available = client.available_phone_numbers.list() phone = available.data[0].phone_number order = client.number_orders.create(phone_numbers=[{"phone_number": phone}]) time.sleep(3)
available = client.available_phone_numbers.list() phone = available.data[0].phone_number order = client.number_orders.create(phone_numbers=[{"phone_number": phone}]) time.sleep(3)

2. Create TeXML app

2. 创建TeXML应用

app = client.texml_applications.create( friendly_name="AI Outbound App", voice_url="https://example.com/placeholder", ) app_id = app.data.id
app = client.texml_applications.create( friendly_name="AI Outbound App", voice_url="https://example.com/placeholder", ) app_id = app.data.id

3. Assign number

3. 绑定号码

requests.patch( f"https://api.telnyx.com/v2/phone_numbers/{phone}", headers=headers, json={"connection_id": app_id}, )
requests.patch( f"https://api.telnyx.com/v2/phone_numbers/{phone}", headers=headers, json={"connection_id": app_id}, )

4. Configure outbound profile

4. 配置外呼配置文件

ovp = requests.get("https://api.telnyx.com/v2/outbound_voice_profiles", headers=headers).json()["data"][0] requests.patch( f"https://api.telnyx.com/v2/outbound_voice_profiles/{ovp['id']}", headers=headers, json={"whitelisted_destinations": ["US", "CA"]}, ) requests.patch( f"https://api.telnyx.com/v2/texml_applications/{app_id}", headers=headers, json={ "friendly_name": "AI Outbound App", "voice_url": "https://example.com/placeholder", "outbound": {"outbound_voice_profile_id": ovp["id"]}, }, )
ovp = requests.get("https://api.telnyx.com/v2/outbound_voice_profiles", headers=headers).json()["data"][0] requests.patch( f"https://api.telnyx.com/v2/outbound_voice_profiles/{ovp['id']}", headers=headers, json={"whitelisted_destinations": ["US", "CA"]}, ) requests.patch( f"https://api.telnyx.com/v2/texml_applications/{app_id}", headers=headers, json={ "friendly_name": "AI Outbound App", "voice_url": "https://example.com/placeholder", "outbound": {"outbound_voice_profile_id": ovp["id"]}, }, )

5. Create assistant with telephony

5. 创建带电话配置的助手

assistant = client.ai.assistants.create( name="Outbound Bot", model="openai/gpt-4o", instructions="You are a helpful phone assistant.", telephony_settings={"default_texml_app_id": app_id}, )
assistant = client.ai.assistants.create( name="Outbound Bot", model="openai/gpt-4o", instructions="你是一位贴心的电话助手。", telephony_settings={"default_texml_app_id": app_id}, )

6. Trigger call

6. 触发通话

client.ai.assistants.scheduled_events.create( assistant_id=assistant.id, telnyx_conversation_channel="phone_call", telnyx_end_user_target="+13125550001", telnyx_agent_target=phone, scheduled_at_fixed_datetime=(datetime.now(timezone.utc) + timedelta(seconds=5)).isoformat(), )
undefined
client.ai.assistants.scheduled_events.create( assistant_id=assistant.id, telnyx_conversation_channel="phone_call", telnyx_end_user_target="+13125550001", telnyx_agent_target=phone, scheduled_at_fixed_datetime=(datetime.now(timezone.utc) + timedelta(seconds=5)).isoformat(), )
undefined

Troubleshooting

问题排查

400: "Assistant does not have telephony settings configured"

400: "Assistant does not have telephony settings configured"

The assistant is missing:
python
telephony_settings={"default_texml_app_id": app_id}
Fix by updating the assistant with
default_texml_app_id
.
助手缺少以下配置:
python
telephony_settings={"default_texml_app_id": app_id}
通过更新助手添加
default_texml_app_id
即可修复。

400: "Cannot make outbound call with no outbound voice profile"

400: "Cannot make outbound call with no outbound voice profile"

The TeXML application does not have an outbound voice profile assigned.
Fix Step 4 above: patch the TeXML app with:
python
"outbound": {"outbound_voice_profile_id": ovp_id}
TeXML应用未绑定外呼语音配置文件。
修复上文的步骤4:为TeXML应用添加以下配置:
python
"outbound": {"outbound_voice_profile_id": ovp_id}

403 with
detail.code == "D13"

403且
detail.code == "D13"

The destination country is not whitelisted on the outbound voice profile.
Fix Step 4 above: add the destination country ISO code to
whitelisted_destinations
.
目标国家未添加到外呼语音配置文件的白名单中。
修复上文的步骤4:将目标国家的ISO编码添加到
whitelisted_destinations

Call never starts / remains pending

通话始终未开始/状态保持pending

Check:
  1. scheduled_at_fixed_datetime
    is in the future and in UTC
  2. telnyx_agent_target
    is your purchased Telnyx number
  3. telnyx_end_user_target
    is the recipient number
  4. The purchased number is assigned to the TeXML app
检查以下项:
  1. scheduled_at_fixed_datetime
    为UTC时区的未来时间
  2. telnyx_agent_target
    是你已购买的Telnyx号码
  3. telnyx_end_user_target
    是正确的被叫号码
  4. 购买的号码已绑定到TeXML应用

422 "not available for inference"

422 "not available for inference"

The selected model is not enabled for your account.
List existing assistants to discover working models:
python
for a in client.ai.assistants.list().data:
    print(a.model)
所选模型未在你的账户中开通。
列出已有助手查询可用模型:
python
for a in client.ai.assistants.list().data:
    print(a.model)