How to Integrate LangChain for healthcare with Stripe for AI agents
Healthcare AI agents usually need two things at the same time: trusted clinical context and a clean way to bill for premium actions. Combining LangChain for healthcare with Stripe gives you a practical pattern for building agents that can answer patient-facing questions, route to approved medical workflows, and charge for usage, subscriptions, or one-off services.
Prerequisites
- •Python 3.10+
- •A LangChain for healthcare project set up with your preferred LLM provider
- •Stripe account with:
- •
STRIPE_SECRET_KEY - •a Product and Price created in the dashboard
- •
- •Access to your healthcare data source or tool layer
- •Environment variables configured in
.env - •Installed packages:
- •
langchain - •
langchain-openaior your model provider package - •
stripe - •
python-dotenv
- •
pip install langchain langchain-openai stripe python-dotenv
Integration Steps
- •Set up environment variables and initialize both SDKs.
You want Stripe billing and LangChain agent execution initialized in the same service boundary. Keep secrets out of code and load them at startup.
import os
from dotenv import load_dotenv
import stripe
load_dotenv()
STRIPE_SECRET_KEY = os.getenv("STRIPE_SECRET_KEY")
OPENAI_API_KEY = os.getenv("OPENAI_API_KEY")
stripe.api_key = STRIPE_SECRET_KEY
os.environ["OPENAI_API_KEY"] = OPENAI_API_KEY
- •Build the healthcare agent with LangChain tools.
For healthcare, keep the agent constrained to approved tools only. If you are using a retrieval layer, wire it as a tool so the model answers from your curated clinical content instead of free-form guessing.
from langchain_openai import ChatOpenAI
from langchain_core.tools import tool
llm = ChatOpenAI(model="gpt-4o-mini", temperature=0)
@tool
def symptom_triage_tool(symptoms: str) -> str:
"""Return a basic triage suggestion from approved clinical guidance."""
return (
f"Reviewed symptoms: {symptoms}. "
"Suggested next step: route to nurse review if red flags are present."
)
tools = [symptom_triage_tool]
If you are using LangChain’s agent interface, bind the tools directly:
from langchain.agents import create_tool_calling_agent, AgentExecutor
from langchain_core.prompts import ChatPromptTemplate, MessagesPlaceholder
prompt = ChatPromptTemplate.from_messages([
("system", "You are a healthcare assistant. Use tools when needed. Do not provide diagnosis."),
("human", "{input}"),
MessagesPlaceholder(variable_name="agent_scratchpad"),
])
agent = create_tool_calling_agent(llm, tools, prompt)
agent_executor = AgentExecutor(agent=agent, tools=tools, verbose=True)
- •Add Stripe billing logic for paid agent actions.
Stripe works best when you treat billing as an explicit step after the agent determines the request is billable. For AI agents, that usually means charging for premium triage, clinician review requests, or report generation.
import stripe
def create_checkout_session(customer_email: str) -> str:
session = stripe.checkout.Session.create(
mode="payment",
customer_email=customer_email,
line_items=[
{
"price": "price_1234567890",
"quantity": 1,
}
],
success_url="https://yourapp.com/success?session_id={CHECKOUT_SESSION_ID}",
cancel_url="https://yourapp.com/cancel",
)
return session.url
If you prefer subscriptions for recurring access to the agent:
def create_subscription_checkout(customer_email: str) -> str:
session = stripe.checkout.Session.create(
mode="subscription",
customer_email=customer_email,
line_items=[
{"price": "price_subscription_abc123", "quantity": 1}
],
success_url="https://yourapp.com/success?session_id={CHECKOUT_SESSION_ID}",
cancel_url="https://yourapp.com/cancel",
)
return session.url
- •Orchestrate the flow: gate premium healthcare actions behind payment.
This is the core integration point. The agent decides whether the request is free or paid, then your app creates a Stripe checkout session before returning premium output.
def handle_patient_request(user_email: str, user_input: str):
result = agent_executor.invoke({"input": user_input})
response_text = result["output"]
billable_keywords = ["nurse review", "second opinion", "detailed report"]
if any(keyword in response_text.lower() for keyword in billable_keywords):
payment_url = create_checkout_session(user_email)
return {
"status": "payment_required",
"message": response_text,
"checkout_url": payment_url,
}
return {
"status": "ok",
"message": response_text,
}
For production systems, do not rely only on keyword checks. Use a classifier step or explicit tool call that marks an action as billable.
- •Verify payment status before unlocking downstream tools.
After Stripe confirms payment via webhook or API lookup, allow the agent to continue with premium workflows like generating a care summary or escalating to a human reviewer.
def verify_checkout_session(session_id: str) -> bool:
session = stripe.checkout.Session.retrieve(session_id)
return session.payment_status == "paid"
def unlock_premium_action(session_id: str):
if not verify_checkout_session(session_id):
return {"status": "blocked", "message": "Payment not completed."}
return {
"status": "unlocked",
"message": "Premium healthcare workflow enabled.",
}
Testing the Integration
Run a simple end-to-end test by sending a request that triggers a billable path and checking Stripe session creation.
if __name__ == "__main__":
test_email = "patient@example.com"
test_input = "I need a detailed report on my symptoms and possible next steps."
result = handle_patient_request(test_email, test_input)
print(result)
if result["status"] == "payment_required":
print("Checkout URL:", result["checkout_url"])
Expected output:
{
'status': 'payment_required',
'message': 'Reviewed symptoms: ... Suggested next step: route to nurse review if red flags are present.',
'checkout_url': 'https://checkout.stripe.com/c/pay/cs_test_...'
}
If you pass a non-billable request, you should see:
{
'status': 'ok',
'message': '...'
}
Real-World Use Cases
- •
Paid symptom triage
- •Let users ask basic health questions through LangChain.
- •Charge for escalations to nurse review or structured care summaries with Stripe Checkout.
- •
Subscription-based care assistant
- •Offer monthly access to an AI health assistant.
- •Use Stripe subscriptions to control access to premium LangChain-powered workflows.
- •
Clinician support portal
- •Generate visit prep notes, medication summaries, or patient intake drafts.
- •Bill clinics per report or per seat while keeping all workflow logic inside your agent layer.
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