broad-garden-14495
03/11/2026, 4:38 PMtall-airline-16756
03/11/2026, 4:39 PMtall-airline-16756
03/11/2026, 4:39 PMimport os
import httpx
from livekit.agents import function_tool, RunContext
@function_tool()
async def send_sms(
self,
context: RunContext,
phone_number: str,
message: str,
) -> str:
# Example: Twilio REST API call (adjust for your provider)
account_sid = os.environ["TWILIO_SID"]
auth_token = os.environ["TWILIO_TOKEN"]
twilio_number = os.environ["TWILIO_FROM"] # your Twilio phone
url = f"<https://api.twilio.com/2010-04-01/Accounts/{account_sid}/Messages.json>"
data = {
"To": phone_number,
"From": twilio_number,
"Body": message,
}
async with httpx.AsyncClient() as client:
resp = await <http://client.post|client.post>(url, data=data, auth=(account_sid, auth_token))
if resp.status_code in (200, 201):
return "SMS sent successfully."
return f"Failed to send SMS: {resp.status_code} {resp.text}"
Tips and considerations
• Protect credentials: use environment variables or a secrets manager (never hard‑code keys).
• Validate phone numbers and user opt‑ins before sending to avoid compliance issues.
• If you need delivery confirmation, use the provider’s webhook callbacks to update message status in your system.
• Include retry logic for transient failures and clear error messages when the provider returns an error.
If you’d like, I can:
• Provide an example adapted to a specific provider (Twilio, AWS SNS, Plivo).
• Show how to register the tool with your agent and an example agent prompt pattern that triggers it.
• Help design webhook handling for delivery receipts.
Which SMS provider do you plan to use, or would you like a recommendation and an example for Twilio?
Sources: Support data sovereignty in India | LiveKit | Handling payments with PCI compliance | LiveKitbroad-garden-14495
03/11/2026, 6:04 PMtall-airline-16756
03/11/2026, 6:05 PMTELNYX_API_KEY and TELNYX_FROM_NUMBER (do not hard-code keys).
import os
import telnyx
from livekit.agents import function_tool, RunContext
# Initialize Telnyx with API key from environment
telnyx.api_key = os.environ["TELNYX_API_KEY"]
FROM_NUMBER = os.environ["TELNYX_FROM_NUMBER"] # e.g. "+1XXXXXXXXXX"
@function_tool()
async def send_sms(
self,
context: RunContext,
to_number: str,
message_body: str,
) -> str:
"""
Send an SMS using Telnyx.
to_number: E.164 formatted recipient number (e.g. "+15551234567")
message_body: Text content to send
"""
try:
msg = telnyx.Message.create(
to=to_number,
from_=FROM_NUMBER,
text=message_body
)
# msg will contain an id and initial status; you may want to persist msg.id
return f"SMS queued (id={msg.id})."
except Exception as e:
# Return error for the agent to surface; log full exception server-side
return f"Failed to send SMS: {str(e)}"
Notes and enhancements
• Phone formatting: Use E.164 format (e.g., +15551234567). Validate before calling the API.
• Credentials: Store TELNYX_API_KEY and TELNYX_FROM_NUMBER in environment variables or a secrets manager.
• Delivery receipts: Telnyx supports webhooks for delivery status. Configure a webhook endpoint to receive callbacks and update message state in your system.
• Error handling & retries: Add retry logic for transient network/provider errors and surface clear messages for permanent failures.
• Rate limits & throughput: Check Telnyx account limits and implement queuing/throttling if you expect high volume.
• Consent & compliance: Ensure users have opted in to receive SMS and follow regional rules (opt-in, opt-out handling, DLT or local registration where required).
• Logging & audit: Log message ids, timestamps, statuses, and any provider errors for debugging and compliance.
If you’d like, I can next:
• Provide a Node.js example instead.
• Show how to wire Telnyx delivery webhooks into your app and map statuses back to the agent.
• Help craft an agent prompt pattern that asks for confirmation before sending SMS (to capture consent).
Which would you prefer next — Node.js sample, webhook handling, or the agent prompt flow?
Sources: Handling payments with PCI compliance | LiveKitbroad-garden-14495
03/12/2026, 10:59 PMtall-airline-16756
03/12/2026, 11:00 PMawait room.connect('<wss://your-project.livekit.cloud>', token);
1. Use short token lifetimes (e.g., minutes) and mint new tokens as needed to reduce risk.
Practical suggestions and best practices
• Token scope: Encode only the minimal permissions (room, participant name, roles) required for each user.
• Room & identity management: Maintain canonical room membership on your backend so you can enforce access rules, recording settings, and moderation.
• Refresh flow: Provide a lightweight endpoint for the frontend to request a fresh token when the current one nears expiration.
• Use HTTPS and secure storage for tokens on clients (e.g., secure cookies or secure storage on mobile).
• Webhooks / server callbacks: If you need events (participant join/leave, recording status), configure server-side webhooks to keep your system in sync.
• Prebuilt UI: If you want faster front-end development, evaluate @livekit/components-react — you can style/extend it so the UX remains within your own app’s look and feel.
• Monitoring & logging: Log token issuance, connection attempts, and failures to help triage auth/connect issues.
If you’d like, I can next:
• Provide a short Node.js or Python example showing how to mint a LiveKit access token on your backend.
• Show a minimal front-end snippet that receives the token and connects using the JS SDK.
• Walk through how to include room permissions/metadata in the token payload.
Which would help most right now — a backend token example (Node/Python), or the front-end connect snippet?broad-garden-14495
03/19/2026, 10:32 PMtall-airline-16756
03/19/2026, 10:32 PMbroad-garden-14495
03/19/2026, 10:33 PMtall-airline-16756
03/19/2026, 10:33 PMbroad-garden-14495
03/19/2026, 10:34 PMtall-airline-16756
03/19/2026, 10:34 PM@function_tool()
async def send_sms(context: RunContext, phone_number: str, message: str) -> str:
import os, requests
api_key = os.getenv("TELNYX_API_KEY")
from_number = os.getenv("TELNYX_FROM_NUMBER") # your Telnyx number
resp = requests.post(
"https://api.telnyx.com/v2/messages",
headers={"Authorization": f"Bearer {api_key}"},
json={
"from": from_number,
"to": phone_number,
"text": message,
"messaging_profile_id": "your_profile_id"
}
)
if resp.ok:
return "SMS sent successfully."
return f"Failed to send SMS: {resp.status_code} {resp.text}"
Inbound SMS handling
• Configure a Telnyx webhook to POST incoming messages to your backend.
• Your backend can create/route messages into the agent’s session or start a new interaction (for example, notify an agent or initiate a callback).
Important considerations
• Consent & compliance: Always verify the user has opted in to SMS. Follow regional rules (e.g., opt‑out handling, DLT registration where required).
• Phone number formatting: Use E.164 (+countrycode) formatting.
• Webhooks: Use webhooks to track delivery status and incoming messages; persist message IDs and statuses for auditing.
• Error handling & retries: Implement retries and proper error logging for provider errors or rate limits.
• Security: Keep Telnyx API keys on your backend or a secrets manager; never expose keys in the frontend.
If you want, I can next:
• Provide a Node.js example for sending SMS via Telnyx and handling webhooks.
• Show how to prompt the caller for SMS consent in a voice flow before sending.
• Walk through wiring Telnyx inbound SMS webhooks into a LiveKit agent session.
Which would help you most right now?
Sources: livekit/livekit_composite | DeepWiki | Telnyx LLM plugin guide | LiveKit Documentation | Agents telephony integration | LiveKit Documentation | Introducing LiveKit Phone Numbers: zero to ringing in 60 seconds | LiveKit | Company directory phone assistant | LiveKit Documentation, with interactive elementsbroad-garden-14495
03/19/2026, 10:38 PMtall-airline-16756
03/19/2026, 10:39 PM/v2/messages) and handles inbound SMS webhooks
• A Python example with the same pieces (token mint, SIP call handling, SMS send/receive)
• A small repo layout or checklist your engineers can fork (env vars, routes, webhook handlers, tests)
• A short agent prompt + function-tool example that asks for SMS consent in voice flow and calls Telnyx when confirmed
One suggested next step
• If you want the Node.js example, tell me: Do you prefer Express or Fastify? Also confirm whether your Telnyx setup will use a messaging profile (recommended). I’ll produce a concise repo-style example (backend + agent tool + webhook handler) you can hand to your engineers.
Which deliverable would help you most right now?
Sources: Telnyx LLM plugin guide | LiveKit Documentation | Introducing LiveKit Phone Numbers: zero to ringing in 60 seconds | LiveKit | Agents telephony integration | LiveKit Documentation | SIP Lifecycle Management Agent | LiveKit Documentation | Prebuilt tools | LiveKit Documentation, with interactive elements