How to Integrate LangChain for lending with Twilio for multi-agent systems
Combining LangChain for lending with Twilio gives you a clean way to build loan workflows that can talk back to borrowers in real time. LangChain handles the reasoning, retrieval, and agent orchestration; Twilio handles SMS and voice delivery across your multi-agent system.
That means you can build things like loan pre-qualification agents, payment reminder agents, and document collection agents that coordinate internally and notify customers externally without hand-rolled glue code.
Prerequisites
- •Python 3.10+
- •A Twilio account with:
- •
TWILIO_ACCOUNT_SID - •
TWILIO_AUTH_TOKEN - •A verified Twilio phone number
- •
- •Access to your lending knowledge base or policy docs
- •LangChain installed with the lending components you use in your stack
- •An LLM provider configured for LangChain
- •A webhook endpoint or local tunnel tool like ngrok if you want inbound SMS replies
- •Environment variables set in
.env
Install the core packages:
pip install langchain twilio python-dotenv fastapi uvicorn
Integration Steps
- •Set up your environment and clients.
You want the lending agent and messaging client initialized once, then reused across requests.
import os
from dotenv import load_dotenv
from twilio.rest import Client as TwilioClient
load_dotenv()
TWILIO_ACCOUNT_SID = os.environ["TWILIO_ACCOUNT_SID"]
TWILIO_AUTH_TOKEN = os.environ["TWILIO_AUTH_TOKEN"]
TWILIO_PHONE_NUMBER = os.environ["TWILIO_PHONE_NUMBER"]
twilio_client = TwilioClient(TWILIO_ACCOUNT_SID, TWILIO_AUTH_TOKEN)
- •Build the lending agent with LangChain.
For lending workflows, keep the agent focused on one task: classify the borrower request, retrieve policy context, and produce a structured response your downstream agents can use.
from langchain_openai import ChatOpenAI
from langchain_core.prompts import ChatPromptTemplate
llm = ChatOpenAI(model="gpt-4o-mini", temperature=0)
prompt = ChatPromptTemplate.from_messages([
("system", "You are a lending operations assistant. Return concise, compliant answers."),
("user", "{customer_message}")
])
lending_chain = prompt | llm
If you are using a lending-specific chain or retriever in your implementation, plug it into this same pattern. The key is to return a clean output that another agent can consume.
- •Add a Twilio notification tool for outbound SMS.
Twilio’s REST API is straightforward. In a multi-agent setup, this becomes the delivery layer for status updates, reminders, and escalation messages.
def send_sms(to_number: str, body: str) -> str:
message = twilio_client.messages.create(
body=body,
from_=TWILIO_PHONE_NUMBER,
to=to_number,
)
return message.sid
Now wire the lending output into SMS delivery:
def handle_borrower_request(customer_message: str, customer_phone: str):
result = lending_chain.invoke({"customer_message": customer_message})
response_text = result.content if hasattr(result, "content") else str(result)
sms_sid = send_sms(
to_number=customer_phone,
body=f"Loan update: {response_text}"
)
return {
"lending_response": response_text,
"sms_sid": sms_sid,
}
- •Orchestrate multiple agents for lending operations.
A practical pattern is:
- •Agent 1 classifies the request
- •Agent 2 checks policy or eligibility logic
- •Agent 3 sends customer-facing updates through Twilio
This keeps each agent narrow and testable.
def classify_request(message: str) -> str:
classification_prompt = ChatPromptTemplate.from_messages([
("system", "Classify the request as: prequalify, status_update, document_request, payment_reminder."),
("user", "{message}")
])
classifier = classification_prompt | llm
result = classifier.invoke({"message": message})
return result.content.strip().lower()
def route_request(customer_message: str, customer_phone: str):
intent = classify_request(customer_message)
if intent == "payment_reminder":
body = "Your payment is due soon. Reply YES if you'd like a callback from our loan team."
sid = send_sms(customer_phone, body)
return {"intent": intent, "sms_sid": sid}
if intent == "document_request":
body = "Please upload your proof of income and ID using the secure portal."
sid = send_sms(customer_phone, body)
return {"intent": intent, "sms_sid": sid}
result = handle_borrower_request(customer_message, customer_phone)
return {"intent": intent, **result}
- •Expose an inbound SMS webhook so borrowers can reply.
Twilio will POST inbound messages to your endpoint. This is where your multi-agent loop starts reacting to real customer input.
from fastapi import FastAPI, Request
from fastapi.responses import PlainTextResponse
app = FastAPI()
@app.post("/twilio/sms")
async def twilio_sms_webhook(request: Request):
form = await request.form()
from_number = form.get("From")
body = form.get("Body")
result = route_request(body, from_number)
return PlainTextResponse(f"Processed intent={result['intent']}")
Run it locally:
uvicorn main:app --reload --port 8000
Then point your Twilio number’s Messaging webhook to:
https://your-ngrok-domain.ngrok.io/twilio/sms
Testing the Integration
Use a direct function call first before testing via Twilio webhooks. That isolates LangChain behavior from delivery issues.
if __name__ == "__main__":
test_phone = "+15551234567"
test_message = "I want to know if I qualify for a personal loan"
result = route_request(test_message, test_phone)
print(result)
Expected output:
{
'intent': 'prequalify',
'lending_response': '...concise lending answer...',
'sms_sid': 'SMXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'
}
If you test through Twilio end-to-end, confirm:
- •The webhook receives the inbound message
- •Your agent returns an intent label or response text
- •An outbound SMS is created successfully with
messages.create(...)
Real-World Use Cases
- •
Loan prequalification triage
- •One agent collects borrower intent.
- •Another evaluates eligibility rules.
- •Twilio sends instant next-step instructions by SMS.
- •
Payment reminder workflows
- •A reminder agent checks due dates.
- •A policy agent decides whether to escalate.
- •Twilio sends reminders and collects reply keywords like
YES,PAY, orCALL ME.
- •
Document collection and escalation
- •A document agent identifies missing items.
- •A compliance agent validates what can be requested over SMS.
- •Twilio delivers secure upload instructions and routes urgent cases to human staff.
The production pattern here is simple: keep LangChain responsible for reasoning and routing, keep Twilio responsible for message delivery, and treat every borrower interaction as an event in a multi-agent workflow. That separation makes the system easier to test, safer to operate, and much easier to extend when lending policies change.
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