How to Integrate LangChain for retail banking with Twilio for multi-agent systems
Retail banking workflows need more than a single chatbot. You usually need one agent to classify the customer intent, another to retrieve policy or account context, and a messaging layer to keep the conversation going across SMS, WhatsApp, or voice callbacks.
That is where LangChain for retail banking and Twilio fit well together. LangChain handles the agent orchestration and tool use, while Twilio gives you the customer-facing channel for multi-agent systems that can answer balance questions, route disputes, and trigger human handoff when needed.
Prerequisites
- •Python 3.10+
- •A virtual environment set up
- •LangChain installed:
- •
pip install langchain langchain-openai
- •
- •Twilio Python SDK installed:
- •
pip install twilio
- •
- •Banking data access layer ready:
- •REST API, internal service, or mock backend for account lookup
- •OpenAI API key or another model provider supported by LangChain
- •Twilio account with:
- •Account SID
- •Auth Token
- •A verified phone number or messaging-enabled sender
- •Optional but recommended:
- •Redis or a database for conversation state
- •Webhook endpoint exposed via ngrok for local testing
Integration Steps
- •
Set up your environment and client objects
Keep secrets in environment variables. In retail banking, do not hardcode credentials or customer data paths in source control.
import os from twilio.rest import Client as TwilioClient from langchain_openai import ChatOpenAI TWILIO_ACCOUNT_SID = os.environ["TWILIO_ACCOUNT_SID"] TWILIO_AUTH_TOKEN = os.environ["TWILIO_AUTH_TOKEN"] TWILIO_PHONE_NUMBER = os.environ["TWILIO_PHONE_NUMBER"] OPENAI_API_KEY = os.environ["OPENAI_API_KEY"] twilio_client = TwilioClient(TWILIO_ACCOUNT_SID, TWILIO_AUTH_TOKEN) llm = ChatOpenAI( model="gpt-4o-mini", api_key=OPENAI_API_KEY, temperature=0 ) - •
Define banking tools as callable functions
For a multi-agent setup, each agent should have narrow responsibilities. One agent can classify intent, another can fetch account data, and another can draft customer-safe responses.
from typing import Dict def get_account_summary(customer_id: str) -> Dict[str, str]: # Replace with your bank's internal API call return { "customer_id": customer_id, "available_balance": "1240.55", "currency": "USD", "status": "active" } def get_dispute_status(case_id: str) -> Dict[str, str]: # Replace with your dispute service call return { "case_id": case_id, "status": "under_review", "eta_days": "3" } - •
Build a LangChain agent that routes banking tasks
Use
create_react_agentwith tools so the LLM can decide which banking action to call. This is the part that makes the system multi-agent friendly: you can later split these tools into separate specialist agents.from langchain_core.tools import tool from langchain.agents import create_react_agent, AgentExecutor from langchain import hub @tool def account_summary(customer_id: str) -> str: """Get a retail banking account summary by customer ID.""" data = get_account_summary(customer_id) return f"Balance: {data['available_balance']} {data['currency']}, Status: {data['status']}" @tool def dispute_status(case_id: str) -> str: """Get dispute status by case ID.""" data = get_dispute_status(case_id) return f"Case {data['case_id']} is {data['status']} with ETA {data['eta_days']} days" tools = [account_summary, dispute_status] prompt = hub.pull("hwchase17/react") agent = create_react_agent(llm=llm, tools=tools, prompt=prompt) executor = AgentExecutor(agent=agent, tools=tools, verbose=True) - •
Connect Twilio inbound messages to the LangChain agent
In production, Twilio hits your webhook when a message arrives. Your webhook should pass the text into the agent and send the result back through Twilio.
from flask import Flask, request, Response app = Flask(__name__) @app.route("/twilio/webhook", methods=["POST"]) def twilio_webhook(): incoming_text = request.form.get("Body", "") from_number = request.form.get("From", "") result = executor.invoke({ "input": f"Customer message from {from_number}: {incoming_text}" }) reply_text = result["output"] twiml_response = f"""<?xml version="1.0" encoding="UTF-8"?>
return Response(twiml_response, mimetype="application/xml")
if name == "main": app.run(port=5000)
5. **Send proactive alerts with Twilio after an agent decision**
This is useful for fraud alerts, low-balance notifications, or dispute updates. The agent decides what happened; Twilio delivers it.
```python
def send_sms_alert(to_number: str, message: str) -> None:
twilio_client.messages.create(
body=message,
from_=TWILIO_PHONE_NUMBER,
to=to_number
)
decision = executor.invoke({
"input": "Check if customer C123 needs a low balance alert."
})
send_sms_alert(
to_number="+15551234567",
message=f"Bank assistant update: {decision['output']}"
)
Testing the Integration
Run a direct agent invocation first before putting Twilio in front of it.
test_result = executor.invoke({
"input": "What is the account summary for customer C123?"
})
print(test_result["output"])
Expected output:
Balance: 1240.55 USD, Status: active
Then test the webhook with a real SMS through your Twilio number. If everything is wired correctly:
- •Twilio receives the inbound message
- •Your Flask webhook gets called
- •LangChain selects the right tool
- •The response goes back as an SMS reply
Real-World Use Cases
- •
Balance and transaction support over SMS
- •Customers ask simple questions by text.
- •One agent fetches account context.
- •Another drafts a compliant response.
- •
Dispute triage and escalation
- •A routing agent classifies chargeback vs card-not-present fraud.
- •A specialist agent checks case status.
- •Twilio sends status updates and handoff messages.
- •
Collections and payment reminders
- •An orchestration agent checks delinquency rules.
- •A messaging agent sends payment reminders via SMS or WhatsApp.
- •Human agents get notified when customers request callback support.
The pattern here is simple: LangChain handles reasoning and tool selection, Twilio handles delivery. In retail banking, that separation matters because you want conversational intelligence without coupling it directly to one channel or one workflow.
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