How to Integrate LangChain for healthcare with Stripe for multi-agent systems

By Cyprian AaronsUpdated 2026-04-22
langchain-for-healthcarestripemulti-agent-systems

LangChain for healthcare gives you the orchestration layer for clinical workflows: triage, summarization, care-plan drafting, and agent handoffs. Stripe gives you the billing rail so those workflows can trigger subscriptions, usage-based charges, or one-off payments when a patient moves from free screening to a paid consult.

The useful pattern here is not “LLM plus payments.” It’s a multi-agent system where one agent handles healthcare context and another handles billing state, with Stripe acting as the source of truth for money movement.

Prerequisites

  • Python 3.10+
  • A LangChain setup for healthcare workflows
    • langchain
    • your healthcare model/provider integration
    • an agent framework such as LangGraph if you’re coordinating multiple agents
  • Stripe account
  • Stripe secret key and webhook signing secret
  • Environment variables configured:
    • STRIPE_SECRET_KEY
    • STRIPE_WEBHOOK_SECRET
  • A database or cache for agent state if you need persistence
  • Basic familiarity with:
    • ChatPromptTemplate
    • tool calling / function calling
    • Stripe Checkout, PaymentIntents, and webhooks

Install the core packages:

pip install langchain stripe fastapi uvicorn pydantic

Integration Steps

1) Initialize Stripe and define a billing tool

Your billing agent should not call Stripe directly from free-form text. Wrap the Stripe SDK in a typed tool so your LangChain agent can invoke it safely.

import os
import stripe
from pydantic import BaseModel, Field

stripe.api_key = os.environ["STRIPE_SECRET_KEY"]

class CreateCheckoutSessionInput(BaseModel):
    customer_email: str = Field(..., description="Patient email")
    amount_cents: int = Field(..., description="Charge amount in cents")
    currency: str = Field(default="usd")
    success_url: str = Field(...)
    cancel_url: str = Field(...)

def create_checkout_session(data: CreateCheckoutSessionInput) -> dict:
    session = stripe.checkout.Session.create(
        mode="payment",
        customer_email=data.customer_email,
        line_items=[
            {
                "price_data": {
                    "currency": data.currency,
                    "product_data": {"name": "Healthcare consultation"},
                    "unit_amount": data.amount_cents,
                },
                "quantity": 1,
            }
        ],
        success_url=data.success_url,
        cancel_url=data.cancel_url,
    )
    return {"id": session.id, "url": session.url, "status": session.status}

This is the clean boundary: LangChain decides when to bill; Stripe executes the charge.

2) Build a healthcare agent that emits billing intents

In a multi-agent setup, your healthcare agent should produce structured output like needs_payment=true rather than directly charging cards. That keeps clinical reasoning separate from financial execution.

from langchain_core.prompts import ChatPromptTemplate
from langchain_core.output_parsers import PydanticOutputParser
from pydantic import BaseModel

class TriageResult(BaseModel):
    summary: str
    urgency: str
    needs_payment: bool
    recommended_service: str

parser = PydanticOutputParser(pydantic_object=TriageResult)

prompt = ChatPromptTemplate.from_messages([
    ("system", "You are a healthcare triage assistant. Return structured output only."),
    ("user", "{patient_note}\n\n{format_instructions}")
])

def triage_patient(llm, patient_note: str) -> TriageResult:
    chain = prompt | llm | parser
    return chain.invoke({
        "patient_note": patient_note,
        "format_instructions": parser.get_format_instructions(),
    })

The output becomes the handoff contract between agents. For example, if the triage agent marks needs_payment=True, the billing agent can create a checkout session.

3) Orchestrate the handoff between agents

Now connect the two flows. The healthcare agent decides whether payment is required; the billing tool creates a Stripe Checkout session only when needed.

from langchain_openai import ChatOpenAI

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

def handle_patient_intake(patient_note: str, patient_email: str):
    triage = triage_patient(llm, patient_note)

    result = {
        "triage": triage.model_dump(),
        "billing": None,
    }

    if triage.needs_payment:
        checkout = create_checkout_session(
            CreateCheckoutSessionInput(
                customer_email=patient_email,
                amount_cents=7500,
                currency="usd",
                success_url="https://yourapp.com/success",
                cancel_url="https://yourapp.com/cancel",
            )
        )
        result["billing"] = checkout

    return result

This pattern scales well in production because each agent has one job:

AgentResponsibilityExternal system
Healthcare agentTriage and care routingLLM + clinical workflow
Billing agentPayment creation and reconciliationStripe
OrchestratorState transitionsYour app / LangGraph

4) Add webhook handling for payment confirmation

Do not trust frontend redirects alone. Use Stripe webhooks to confirm payment completion and update your agent state after payment succeeds.

from fastapi import FastAPI, Request, HTTPException

app = FastAPI()

@app.post("/webhooks/stripe")
async def stripe_webhook(request: Request):
    payload = await request.body()
    sig_header = request.headers.get("stripe-signature")

    try:
        event = stripe.Webhook.construct_event(
            payload=payload,
            sig_header=sig_header,
            secret=os.environ["STRIPE_WEBHOOK_SECRET"],
        )
    except Exception as e:
        raise HTTPException(status_code=400, detail=str(e))

    if event["type"] == "checkout.session.completed":
        session = event["data"]["object"]
        # Mark payment complete in your DB / workflow engine here.
        return {"received": True, "session_id": session["id"]}

    return {"received": True}

If you’re using LangGraph or another state machine, this webhook becomes the signal that moves the patient workflow from “awaiting payment” to “consultation ready.”

5) Expose a single API endpoint for intake + billing

Your app should present one endpoint that triggers both orchestration and payment creation when needed.

from fastapi import FastAPI
from pydantic import BaseModel

app = FastAPI()

class IntakeRequest(BaseModel):
    patient_note: str
    patient_email: str

@app.post("/intake")
def intake(req: IntakeRequest):
    return handle_patient_intake(req.patient_note, req.patient_email)

That gives frontend clients one entry point while keeping internal responsibilities split across agents.

Testing the Integration

Run a local test with a sample symptom note and verify that you get both triage output and a Stripe Checkout URL when payment is required.

if __name__ == "__main__":
    response = handle_patient_intake(
        patient_note="Patient reports persistent cough for 10 days and wants same-day telehealth review.",
        patient_email="patient@example.com",
    )
    print(response)

Expected output:

{
  'triage': {
    'summary': 'Persistent cough requiring clinician review',
    'urgency': 'medium',
    'needs_payment': True,
    'recommended_service': 'telehealth_consultation'
  },
  'billing': {
    'id': 'cs_test_123',
    'url': 'https://checkout.stripe.com/c/pay/cs_test_123',
    'status': 'open'
  }
}

If needs_payment is false, billing should be None. That tells you your orchestration logic is working before you wire in real users.

Real-World Use Cases

  • Paid telehealth intake

    • A triage agent screens symptoms.
    • If the case needs clinician review, Stripe Checkout collects payment before scheduling.
  • Subscription-based care plans

    • One agent monitors patient requests.
    • Another checks subscription status through Stripe Customer Portal or billing records before granting premium access.
  • Usage-based AI support for providers

    • Healthcare staff query an internal assistant.
    • Billing events are tracked in Stripe based on consult volume or document generation volume.

The main design rule is simple: let LangChain decide what should happen next, and let Stripe handle money movement. Keep those boundaries clean and your multi-agent system stays auditable.


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