telnyx-ai-outbound-voice-python
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseTelnyx 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 requestsbash
pip install telnyx requestsSetup
配置
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.
- A purchased Telnyx phone number
- A TeXML application
- The phone number assigned to the TeXML application
- An outbound voice profile with destination countries whitelisted
- An AI assistant with set to the TeXML app
telephony_settings.default_texml_app_id
外呼语音通话需要满足所有以下条件,缺少任意一项都会返回对应的错误——参见问题排查。
- 已购买的Telnyx电话号码
- 一个TeXML应用
- 电话号码已绑定到TeXML应用
- 已配置目标国家白名单的外呼语音配置文件
- AI助手的已设置为对应TeXML应用ID
telephony_settings.default_texml_app_id
Model availability
模型可用性
Model availability varies by account. If returns
422 "not available for inference", discover working models from existing assistants:
client.ai.assistants.create()python
for a in client.ai.assistants.list().data:
print(a.model)Commonly available: , .
openai/gpt-4oQwen/Qwen3-235B-A22B模型可用性因账户而异。如果返回422错误「not available for inference」,可以从现有助手列表中查询可用模型:
client.ai.assistants.create()python
for a in client.ai.assistants.list().data:
print(a.model)常见可用模型:、。
openai/gpt-4oQwen/Qwen3-235B-A22BStep 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 is required by the API but is not used for outbound AI assistant calls.
The TeXML app ID is also used as the when assigning phone numbers.
voice_urlconnection_idpython
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 assignmentAPI要求传入参数,但AI助手外呼场景不会使用该地址。TeXML应用ID同时也会作为绑定电话号码时使用的。
voice_urlconnection_idpython
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_idStep 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},
},
)
undefinedrequests.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},
},
)
undefinedStep 5: Create the AI assistant with telephony settings
步骤5:创建带电话配置的AI助手
telephony_settingsdefault_texml_app_idscheduled_events.create()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},
)外呼功能必须配置包含的。缺少该配置时,会返回400错误「Assistant does not have telephony settings configured」。
default_texml_app_idtelephony_settingsscheduled_events.create()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 with a time a few seconds in the future for
an immediate call.
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", # 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"| Parameter | Type | Required | Description |
|---|---|---|---|
| string (UUID) | Yes | The AI assistant that handles the call. |
| string | Yes | Must be |
| string (E.164) | Yes | Phone number to call (recipient). |
| string (E.164) | Yes | Your Telnyx number (caller ID). Must be assigned to the TeXML app. |
| string (ISO 8601) | Yes | When to place the call. ~5s in the future for immediate. |
| object | No | Variables to pass to the assistant. |
| object | No | Metadata 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"| 参数 | 类型 | 是否必填 | 描述 |
|---|---|---|---|
| string (UUID) | 是 | 处理通话的AI助手ID。 |
| string | 是 | 必须为 |
| string (E.164) | 是 | 被叫号码(接收方)。 |
| string (E.164) | 是 | 你的Telnyx号码(主叫ID),必须已绑定到TeXML应用。 |
| string (ISO 8601) | 是 | 发起通话的时间,如需立即拨打可设置为未来约5秒。 |
| object | 否 | 传递给助手的变量。 |
| 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(),
)
undefinedclient.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(),
)
undefinedTroubleshooting
问题排查
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_id400: "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"
detail.code == "D13"403且detail.code == "D13"
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_destinationsCall never starts / remains pending
通话始终未开始/状态保持pending
Check:
- is in the future and in UTC
scheduled_at_fixed_datetime - is your purchased Telnyx number
telnyx_agent_target - is the recipient number
telnyx_end_user_target - The purchased number is assigned to the TeXML app
检查以下项:
- 为UTC时区的未来时间
scheduled_at_fixed_datetime - 是你已购买的Telnyx号码
telnyx_agent_target - 是正确的被叫号码
telnyx_end_user_target - 购买的号码已绑定到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)