How to Integrate LangChain for lending with SendGrid for multi-agent systems

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

Combining LangChain for lending with SendGrid gives you a clean path from loan decisioning to customer communication. In a multi-agent system, one agent can assess borrower context, another can draft the explanation, and SendGrid handles delivery of approval, denial, or document-request emails without building a separate notification service.

Prerequisites

  • Python 3.10+
  • A LangChain for lending project set up with your lender workflows and agent tools
  • A SendGrid account with an API key
  • Verified sender identity in SendGrid
  • Environment variables configured:
    • SENDGRID_API_KEY
    • FROM_EMAIL
    • TO_EMAIL
  • Installed packages:
    • langchain
    • sendgrid
    • any lender-specific LangChain integration package you use for your lending agents

Integration Steps

  1. Install dependencies

    Start by installing the SDKs your agent will use. If your lending workflow is already built on LangChain, you only need the SendGrid client on top of it.

    pip install langchain sendgrid python-dotenv
    
  2. Set up environment variables and the SendGrid client

    Keep secrets out of code. Build the email client once and reuse it across agents or worker processes.

    import os
    from dotenv import load_dotenv
    from sendgrid import SendGridAPIClient
    
    load_dotenv()
    
    SENDGRID_API_KEY = os.getenv("SENDGRID_API_KEY")
    FROM_EMAIL = os.getenv("FROM_EMAIL")
    TO_EMAIL = os.getenv("TO_EMAIL")
    
    sg = SendGridAPIClient(SENDGRID_API_KEY)
    
  3. Build a lending agent that returns structured decision data

    In a multi-agent setup, your lending agent should not send email directly. It should return structured output that another agent can consume.

    Below is a simple pattern using LangChain’s ChatPromptTemplate, RunnableLambda, and JsonOutputParser to produce a decision payload.

    from langchain_core.prompts import ChatPromptTemplate
    from langchain_core.output_parsers import JsonOutputParser
    from langchain_openai import ChatOpenAI
    
    llm = ChatOpenAI(model="gpt-4o-mini", temperature=0)
    
    prompt = ChatPromptTemplate.from_messages([
        ("system", "You are a lending decision assistant. Return only valid JSON."),
        ("user", """
        Evaluate this application:
        Name: {name}
        Credit Score: {credit_score}
        Income: {income}
        Loan Amount: {loan_amount}
    
        Return JSON with keys:
        decision (approved|declined|needs_review),
        reason,
        next_action,
        customer_message
        """)
    ])
    
    parser = JsonOutputParser()
    lending_chain = prompt | llm | parser
    
    result = lending_chain.invoke({
        "name": "Amina Khan",
        "credit_score": 712,
        "income": 92000,
        "loan_amount": 15000
    })
    
    print(result)
    
  4. Create an email sender agent that maps loan outcomes to SendGrid messages

    This is where the integration happens. The second agent takes the structured result and sends an email using SendGridAPIClient.send() with a Mail object.

     from sendgrid.helpers.mail import Mail, Email, To, Content
    
     def send_decision_email(decision_payload: dict) -> str:
         subject_map = {
             "approved": "Your loan application was approved",
             "declined": "Your loan application update",
             "needs_review": "Your loan application needs review"
         }
    
         subject = subject_map.get(decision_payload["decision"], "Loan application update")
    
         message = Mail(
             from_email=Email(FROM_EMAIL),
             to_emails=To(TO_EMAIL),
             subject=subject,
             plain_text_content=Content(
                 "text/plain",
                 f"{decision_payload['customer_message']}\n\nReason: {decision_payload['reason']}\nNext action: {decision_payload['next_action']}"
             )
         )
    
         response = sg.send(message)
         return f"SendGrid status: {response.status_code}"
    
     email_status = send_decision_email(result)
     print(email_status)
    
  5. Wire both agents together in a single orchestration flow

    In production, keep orchestration explicit. One agent decides, another communicates. That separation makes retries, auditing, and compliance easier.

     def process_loan_application(application: dict) -> dict:
         decision = lending_chain.invoke(application)
         email_status = send_decision_email(decision)
    
         return {
             "application_id": application.get("application_id", "unknown"),
             "decision": decision,
             "email_status": email_status
         }
    
     application = {
         "application_id": "LN-10021",
         "name": "Amina Khan",
         "credit_score": 712,
         "income": 92000,
         "loan_amount": 15000
     }
    
     output = process_loan_application(application)
     print(output)
    

Testing the Integration

Run a local smoke test with a known-good payload. If you want to avoid sending real mail during development, point TO_EMAIL to a test inbox or mock sg.send() in unit tests.

test_application = {
    "application_id": "TEST-001",
    "name": "Jordan Lee",
    "credit_score": 780,
    "income": 115000,
    "loan_amount": 10000
}

response = process_loan_application(test_application)
print(response)

Expected output:

{
  'application_id': 'TEST-001',
  'decision': {
    'decision': 'approved',
    'reason': 'Strong credit profile and income support the requested amount.',
    'next_action': 'Send approval notice and funding instructions.',
    'customer_message': 'Your loan application has been approved.'
  },
  'email_status': 'SendGrid status: 202'
}

If you get 202, SendGrid accepted the message for delivery.

Real-World Use Cases

  • Loan approval notifications

    • One agent evaluates eligibility.
    • Another sends approval or denial emails with compliant wording and next steps.
  • Document collection workflows

    • A document-review agent detects missing bank statements or ID verification.
    • SendGrid sends targeted follow-ups with upload links and deadlines.
  • Multi-agent underwriting pipelines

    • Separate agents handle risk scoring, fraud checks, and final communication.
    • The communication agent uses SendGrid to notify borrowers, brokers, or internal ops teams based on the final state.

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