How to Integrate LangChain for retail banking with Twilio for AI agents
Retail banking teams need two things from an AI agent: access to the right internal context and a reliable channel to reach customers. LangChain handles the retrieval, orchestration, and tool use; Twilio handles SMS, voice, and WhatsApp delivery. Put them together and you can build agents that answer balance questions, collect intent, and push secure follow-ups over a channel customers already use.
Prerequisites
- •Python 3.10+
- •A Twilio account with:
- •
TWILIO_ACCOUNT_SID - •
TWILIO_AUTH_TOKEN - •A verified
TWILIO_PHONE_NUMBER
- •
- •Access to your retail banking data source:
- •FAQ docs, product PDFs, policy pages, or CRM exports
- •LangChain installed with the integrations you need:
- •
langchain - •
langchain-community - •
langchain-openaior another LLM provider
- •
- •An embedding model and vector store for retrieval:
- •FAISS, Chroma, Pinecone, or similar
- •Environment variables set locally:
- •
OPENAI_API_KEY - •
TWILIO_ACCOUNT_SID - •
TWILIO_AUTH_TOKEN - •
TWILIO_PHONE_NUMBER
- •
Install the core packages:
pip install langchain langchain-community langchain-openai twilio faiss-cpu python-dotenv
Integration Steps
- •Load retail banking knowledge into LangChain
Start by indexing your banking content so the agent can answer from approved sources instead of guessing.
import os
from dotenv import load_dotenv
from langchain_community.document_loaders import TextLoader
from langchain_text_splitters import RecursiveCharacterTextSplitter
from langchain_community.vectorstores import FAISS
from langchain_openai import OpenAIEmbeddings
load_dotenv()
loader = TextLoader("retail_banking_faq.txt", encoding="utf-8")
docs = loader.load()
splitter = RecursiveCharacterTextSplitter(chunk_size=800, chunk_overlap=120)
chunks = splitter.split_documents(docs)
embeddings = OpenAIEmbeddings(model="text-embedding-3-small")
vectorstore = FAISS.from_documents(chunks, embeddings)
retriever = vectorstore.as_retriever(search_kwargs={"k": 3})
This gives your agent a controlled knowledge base for product terms, fees, card replacement flows, branch hours, and dispute procedures.
- •Create a LangChain retrieval chain for customer questions
Use a chat model plus retrieval to generate grounded answers.
from langchain_openai import ChatOpenAI
from langchain.chains import RetrievalQA
llm = ChatOpenAI(model="gpt-4o-mini", temperature=0)
qa_chain = RetrievalQA.from_chain_type(
llm=llm,
chain_type="stuff",
retriever=retriever,
return_source_documents=True,
)
question = "How do I replace a lost debit card?"
result = qa_chain.invoke({"query": question})
print(result["result"])
In retail banking, this is the core pattern: retrieve policy-approved context first, then generate the response. Do not let the model answer from memory alone.
- •Set up Twilio for outbound SMS notifications
Twilio is what turns your agent into an operational system. Use it to send confirmations, case updates, OTP handoffs, or callback links.
import os
from twilio.rest import Client
twilio_client = Client(
os.environ["TWILIO_ACCOUNT_SID"],
os.environ["TWILIO_AUTH_TOKEN"],
)
message = twilio_client.messages.create(
body="Your card replacement request has been received. Reply YES to confirm a callback.",
from_=os.environ["TWILIO_PHONE_NUMBER"],
to="+15551234567",
)
print(message.sid)
For production banking flows, keep outbound messages short and avoid sensitive account details in plain SMS.
- •Wrap LangChain output into a Twilio-delivered agent response
Now connect the two: answer with LangChain, then send that answer through Twilio.
def answer_and_send_sms(user_phone: str, user_question: str):
result = qa_chain.invoke({"query": user_question})
answer = result["result"]
sms = twilio_client.messages.create(
body=f"Bank Assistant: {answer}",
from_=os.environ["TWILIO_PHONE_NUMBER"],
to=user_phone,
)
return {
"answer": answer,
"message_sid": sms.sid,
"sources": [doc.metadata.get("source", "unknown") for doc in result["source_documents"]],
}
response = answer_and_send_sms(
"+15551234567",
"What is the daily limit for mobile check deposits?",
)
print(response)
This pattern works well when your agent resolves an issue in-app but still needs to notify the customer asynchronously via SMS.
- •Add an inbound Twilio webhook so customers can talk back
For real agent workflows, Twilio should receive inbound messages and route them into LangChain.
from flask import Flask, request
from twilio.twiml.messaging_response import MessagingResponse
app = Flask(__name__)
@app.route("/sms", methods=["POST"])
def sms_webhook():
incoming_text = request.form.get("Body", "")
sender = request.form.get("From", "")
result = qa_chain.invoke({"query": incoming_text})
reply_text = result["result"]
twiml_response = MessagingResponse()
twiml_response.message(reply_text)
return str(twiml_response)
if __name__ == "__main__":
app.run(port=5000)
Point your Twilio number’s messaging webhook at /sms, then forward customer text into your LangChain retrieval flow. That gives you a simple conversational banking entry point without building a custom mobile UI first.
Testing the Integration
Run a direct test before wiring up webhooks. This verifies both retrieval and Twilio delivery.
test_phone = "+15551234567"
test_question = "What documents do I need to open a savings account?"
output = answer_and_send_sms(test_phone, test_question)
print("Answer:", output["answer"])
print("Message SID:", output["message_sid"])
print("Sources:", output["sources"])
Expected output:
Answer: You typically need a government-issued ID, proof of address, and your tax identification details.
Message SID: SMXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
Sources: ['retail_banking_faq.txt']
If the message SID appears and the answer is grounded in your approved content, the integration is working end to end.
Real-World Use Cases
- •
Card servicing assistant
- •Customers text “lost card” or “replace my card,” and the agent retrieves policy steps from LangChain while Twilio sends status updates and callback confirmations.
- •
Deposit and fee support
- •The agent answers questions about mobile deposit limits, overdraft fees, transfer timing, and branch availability using bank-approved knowledge sources.
- •
Lead capture and appointment routing
- •A customer asks about opening an account; the agent qualifies intent through LangChain and uses Twilio SMS or WhatsApp to send next steps or schedule links.
Keep learning
- •The complete AI Agents Roadmap — my full 8-step breakdown
- •Free: The AI Agent Starter Kit — PDF checklist + starter code
- •Work with me — I build AI for banks and insurance companies
By Cyprian Aarons, AI Consultant at Topiax.
Want the complete 8-step roadmap?
Grab the free AI Agent Starter Kit — architecture templates, compliance checklists, and a 7-email deep-dive course.
Get the Starter Kit