An SMS AI agent is a webhook server that sits between a phone number and a large language model. Twilio receives the text, POSTs it to your endpoint, your code checks it, asks the LLM for a reply and sends that reply back as an SMS. The code is small; the parts that trip people up are carrier registration, opt-out handling and keeping replies short enough to be cheap.
This guide walks through a minimal working version in Python, based on Twilio's official documentation. It is a starting point, not a production system. For the bigger picture (state, memory, human handoff), see our SMS agent architecture guide.
What does the message path look like?
Every inbound text follows the same route. Knowing it makes debugging much easier.
- Customer's phone
- Carrier
- Twilio number
- Your webhook
- LLM
- Twilio Messages API
Twilio sends your webhook a form-encoded POST with fields including From, To, Body and MessageSid. You reply either by returning TwiML in the HTTP response or by calling the Messages API separately. The second option is better when the model takes more than a few seconds.
What do you need before writing code?
- Buy a numberGet an SMS-capable US local or toll-free number in the Twilio Console.
- Register for A2PSubmit a 10DLC brand and campaign (local numbers) or toll-free verification.
- Expose an HTTPS endpointDeploy a small web app or use a tunnel during development.
- Set the webhookPoint the number's "A message comes in" URL at your endpoint.
- Pick an LLMAny chat-completion API works; keep the key server-side.
Registration is the slow part. Unregistered 10DLC traffic is filtered by carriers and, on Twilio, incurs extra carrier fees, according to Twilio's A2P 10DLC docs. Start it on day one. Our 10DLC registration guide for AI chatbots covers what reviewers look for.
How do you write the webhook?
Below is a minimal Flask app. It validates the Twilio signature, handles opt-out and help keywords in code, keeps a short history per phone number and asks an LLM for a reply. The call_llm function is a placeholder for whichever provider you use.
import os
from flask import Flask, request, abort
from twilio.request_validator import RequestValidator
from twilio.twiml.messaging_response import MessagingResponse
app = Flask(__name__)
validator = RequestValidator(os.environ["TWILIO_AUTH_TOKEN"])
OPT_OUT = {"stop", "quit", "end", "revoke", "opt out", "cancel", "unsubscribe"}
HISTORY = {} # use Redis or a database in production
OPTED_OUT = set() # persist this; it is a legal record
SYSTEM = ("You are the SMS assistant for Acme Dental. Answer in at most "
"2 short sentences. Never ask for card numbers or passwords.")
@app.post("/sms")
def sms():
sig = request.headers.get("X-Twilio-Signature", "")
if not validator.validate(request.url, request.form, sig):
abort(403)
sender = request.form["From"]
body = request.form.get("Body", "").strip()
resp = MessagingResponse()
if body.lower() in OPT_OUT:
OPTED_OUT.add(sender)
return str(resp) # Twilio's default opt-out handling can send the confirmation
if body.lower() == "help":
resp.message("Acme Dental: call 555-0100 or reply STOP to opt out.")
return str(resp)
if sender in OPTED_OUT:
return str(resp)
history = HISTORY.setdefault(sender, [])[-10:]
history.append({"role": "user", "content": body})
reply = call_llm(system=SYSTEM, messages=history)[:320]
history.append({"role": "assistant", "content": reply})
HISTORY[sender] = history
resp.message(reply)
return str(resp)
A few notes on what this does and does not do:
- Signature validation uses Twilio's
RequestValidator. Twilio's webhook security docs say it signs each request with HMAC-SHA1 using your auth token, and advise using the SDK rather than writing your own check. If you sit behind a proxy, make surerequest.urlmatches the public URL Twilio called. - Keywords before the model. The opt-out list mirrors the seven standardized words in the FCC's 2026 revocation order. Twilio's Advanced Opt-Out feature can also handle these at the platform level. Either way, the LLM should never decide whether someone has opted out. See SMS opt-in and opt-out rules.
- Truncation to 320 characters caps a reply at about two GSM-7 segments. A better approach is a strict prompt plus a hard limit.
Do not trust the From number as identity. Caller ID and sender numbers can be spoofed, so require a login link or one-time code before an agent reveals account data or takes a high-risk action. Our guide to SMS spoofing and AI agents explains why.
How do you handle slow LLM responses?
Twilio expects your webhook to respond quickly. If your agent calls tools (a calendar, a CRM) or a large model, return an empty TwiML response straight away and send the answer from a background job:
from twilio.rest import Client
client = Client(os.environ["TWILIO_ACCOUNT_SID"], os.environ["TWILIO_AUTH_TOKEN"])
def send_later(to, text):
client.messages.create(
to=to,
messaging_service_sid=os.environ["MESSAGING_SERVICE_SID"],
body=text,
)
Sending through a Messaging Service ties the message to your registered 10DLC campaign. Add a status callback URL if you want delivery receipts.
What does it cost to run?
Costs are per segment, not per conversation. Message prices are Twilio's published US pricing as of November 2026; the 10DLC fees are per Twilio's help centre, as of 2026:
- Twilio per SMS segment, in or out
- $0.0083
- Typical US carrier fee per message
- $0.0025–$0.007
- One-time 10DLC brand fee
- $4.50–$46
- One-time campaign vetting fee
- $15
A simple one-segment question and one-segment answer comes to roughly $0.024 to $0.03 including carrier fees, before LLM tokens. That figure is our arithmetic from Twilio's list prices, not a quoted number. Long replies, emoji (which force UCS-2 encoding and 70-character segments) and MMS raise it quickly. Our SMS AI agent cost breakdown has worked examples.
Should you build it yourself or use a managed SDK?
The hand-rolled approach above gives you full control and the lowest cost. The trade-off is that you own memory, retries, handoff and channel differences.
Twilio made Agent Connect generally available in May 2026. It is a Python and TypeScript SDK that bundles conversation memory and orchestration across SMS, WhatsApp, RCS and voice. If you need several channels, it may save time. Our Agent Connect explainer covers what it includes. For voice specifically, see our ConversationRelay explainer. For WhatsApp, the Cloud API guide covers Meta's rules, which differ from SMS.
Pros
- Full control over prompts, models and data retention
- Lowest per-message cost
- Easy to add your own tools
Cons
- You build memory, retries and human handoff yourself
- Each channel needs its own compliance work
- Security (prompt injection, spoofing) is entirely on you
What should you add before going live?
- Persistent storage for history and, above all, opt-out records.
- Prompt-injection defences. Anyone can text your number. Treat every inbound message as untrusted, give the model only the tools it needs and require confirmation for anything that changes data. Our guide to prompt injection through text messages goes deeper, and getpersonalaiagents.com has a general explainer on prompt injection.
- A human handoff path, such as replying "AGENT" to reach staff.
- Logging and rate limits per sender, so one number cannot run up your LLM bill.
- Consent records. The CTIA guidelines recommend keeping the timestamp, method and wording of each opt-in.
Bottom line
A working SMS AI agent is about 50 lines of code. Registration, opt-out handling, short replies and basic security take most of the effort, and they decide whether your messages get delivered. Build the webhook in an afternoon, but start 10DLC registration first and handle STOP in code, not in the prompt.



