How to Integrate LangChain for banking with Twilio for multi-agent systems

By Cyprian AaronsUpdated 2026-04-21
langchain-for-bankingtwiliomulti-agent-systems

Connecting LangChain for banking with Twilio gives you a practical control plane for customer-facing AI agents. LangChain handles the reasoning, tool orchestration, and retrieval over banking workflows, while Twilio gives you the delivery layer for SMS, WhatsApp, and voice notifications.

This combo is useful when one agent needs to answer account questions, another needs to trigger alerts, and a human fallback must be notified over a channel the customer already uses.

Prerequisites

  • Python 3.10+
  • A LangChain-based banking app or agent service already set up
  • A Twilio account with:
    • TWILIO_ACCOUNT_SID
    • TWILIO_AUTH_TOKEN
    • a verified TWILIO_PHONE_NUMBER
  • Bank-side tools or APIs exposed as callable functions
  • Environment variables configured in .env
  • Installed packages:
    • langchain
    • langchain-openai
    • twilio
    • python-dotenv
pip install langchain langchain-openai twilio python-dotenv

Integration Steps

  1. Load configuration and initialize Twilio

Start by loading secrets from environment variables and creating a Twilio client. Keep this outside your agent logic so you can reuse it across multiple agents.

import os
from dotenv import load_dotenv
from twilio.rest import Client

load_dotenv()

twilio_client = Client(
    os.environ["TWILIO_ACCOUNT_SID"],
    os.environ["TWILIO_AUTH_TOKEN"],
)

TWILIO_FROM_NUMBER = os.environ["TWILIO_PHONE_NUMBER"]
  1. Wrap Twilio messaging as a LangChain tool

In a multi-agent banking system, the safest pattern is to expose Twilio as a narrow tool. The agent should decide when to notify, but the tool should only do one thing: send a message.

from langchain_core.tools import tool

@tool
def send_sms(to_number: str, message: str) -> str:
    """Send an SMS notification through Twilio."""
    msg = twilio_client.messages.create(
        body=message,
        from_=TWILIO_FROM_NUMBER,
        to=to_number,
    )
    return f"SMS sent with SID {msg.sid}"

If you also need WhatsApp notifications, define a second tool using the same client.

@tool
def send_whatsapp(to_number: str, message: str) -> str:
    """Send a WhatsApp message through Twilio."""
    msg = twilio_client.messages.create(
        body=message,
        from_="whatsapp:" + TWILIO_FROM_NUMBER,
        to="whatsapp:" + to_number,
    )
    return f"WhatsApp sent with SID {msg.sid}"
  1. Create the banking agent with LangChain tools

For banking workflows, keep your core agent focused on retrieval and policy-compliant actions. In this example, we wire in both a banking lookup tool and the Twilio notification tool.

from langchain_openai import ChatOpenAI
from langchain_core.prompts import ChatPromptTemplate
from langchain.agents import create_tool_calling_agent, AgentExecutor

def get_account_balance(account_id: str) -> str:
    # Replace with real bank API call
    return f"Account {account_id} balance is USD 12,450.22"

@tool
def bank_balance_lookup(account_id: str) -> str:
    """Fetch account balance for a customer."""
    return get_account_balance(account_id)

llm = ChatOpenAI(model="gpt-4o-mini", temperature=0)

prompt = ChatPromptTemplate.from_messages([
    ("system", "You are a banking assistant. Use tools only when needed."),
    ("human", "{input}"),
])

tools = [bank_balance_lookup, send_sms]

agent = create_tool_calling_agent(llm=llm, tools=tools, prompt=prompt)
agent_executor = AgentExecutor(agent=agent, tools=tools, verbose=True)
  1. Coordinate multiple agents through shared events

In multi-agent systems, don’t let every agent talk to Twilio directly. Use one orchestrator agent to decide when an alert should be sent, then route that action through the notification tool.

def handle_low_balance_alert(account_id: str, phone_number: str):
    result = agent_executor.invoke({
        "input": (
            f"Check balance for account {account_id}. "
            f"If balance is below 1000 USD, notify {phone_number} by SMS."
        )
    })
    return result["output"]

print(handle_low_balance_alert("ACCT-10021", "+15551234567"))

If you have separate agents for fraud detection and customer support, keep them isolated and let each emit structured events into the same notification layer.

def fraud_agent_decision(transaction_id: str) -> dict:
    # Example output from a fraud-scoring agent
    return {
        "risk": "high",
        "reason": "Unusual transfer velocity detected",
        "customer_phone": "+15551234567",
    }

decision = fraud_agent_decision("TXN-88391")

if decision["risk"] == "high":
    send_sms.invoke({
        "to_number": decision["customer_phone"],
        "message": f"Alert: suspicious activity detected. Reason: {decision['reason']}"
    })

Testing the Integration

Use a controlled test number first. The goal is to verify that LangChain can trigger the Twilio tool and that Twilio returns a valid message SID.

test_result = agent_executor.invoke({
    "input": (
        "Check balance for account ACCT-10021. "
        "If it is below 20000 USD, send an SMS alert to +15551234567."
    )
})

print(test_result["output"])

Expected output:

Account ACCT-10021 balance is USD 12,450.22
SMS sent with SID SMXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

If you want to test just the messaging path without the full agent loop:

sms_result = send_sms.invoke({
    "to_number": "+15551234567",
    "message": "Test alert from banking agent integration"
})

print(sms_result)

Expected output:

SMS sent with SID SMXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

Real-World Use Cases

  • Low-balance alerts with human escalation
    One agent checks balances or transaction state; another sends SMS or WhatsApp alerts when thresholds are crossed.

  • Fraud triage across multiple agents
    A fraud-scoring agent flags suspicious activity, then Twilio notifies both the customer and an internal analyst queue.

  • Customer service handoff
    The conversational agent resolves simple requests in-chat and uses Twilio voice or SMS to escalate high-risk cases to an advisor.


Keep learning

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

Related Guides