How to Integrate LangChain for banking with Stripe for RAG
Combining LangChain for banking with Stripe gives you a clean path to build agents that can answer customer questions, retrieve policy or transaction context, and trigger payment-related workflows without hardcoding every branch. In practice, this is useful for things like payment status lookup, invoice reconciliation, subscription support, and fraud-review assistants that need retrieval-augmented generation (RAG) plus a real billing system behind them.
Prerequisites
- •Python 3.10+
- •A LangChain banking setup with:
- •access to your banking knowledge base
- •a retriever or vector store for RAG
- •Stripe account with:
- •API secret key
- •test mode enabled
- •at least one test customer or payment intent
- •Installed packages:
- •
langchain - •
langchain-openaior your model provider package - •
stripe - •
python-dotenv
- •
- •Environment variables configured:
- •
OPENAI_API_KEY - •
STRIPE_SECRET_KEY
- •
Install the dependencies:
pip install langchain langchain-openai stripe python-dotenv
Integration Steps
- •
Set up your Stripe client and load environment variables
Keep the Stripe client isolated from your LLM logic. That makes retries, logging, and test/prod switching easier.
import os
from dotenv import load_dotenv
import stripe
load_dotenv()
stripe.api_key = os.environ["STRIPE_SECRET_KEY"]
- •
Build the banking RAG retriever in LangChain
For banking use cases, you usually want the agent to retrieve from policy docs, fee schedules, account FAQs, or internal SOPs before taking any action. Here’s a minimal retriever setup using FAISS and OpenAI embeddings.
from langchain_community.vectorstores import FAISS
from langchain_openai import OpenAIEmbeddings
from langchain_core.documents import Document
docs = [
Document(page_content="Stripe payments are used for card charges and invoice collection."),
Document(page_content="Refund requests over $500 require manual approval."),
Document(page_content="Failed payments should be retried after checking customer funding source."),
]
embeddings = OpenAIEmbeddings()
vectorstore = FAISS.from_documents(docs, embeddings)
retriever = vectorstore.as_retriever(search_kwargs={"k": 2})
- •
Create a LangChain chain that uses retrieved context to decide on a Stripe action
This is the core pattern: retrieve relevant banking context first, then ask the model to produce structured intent. In production, keep the model output constrained so you can map it safely to Stripe calls.
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 banking operations assistant. Use retrieved context to decide if a Stripe refund should be issued."),
("human", "Context:\n{context}\n\nCustomer request:\n{question}\n\nReturn JSON with keys: action, reason, amount_cents.")
])
def build_rag_decision(question: str):
docs = retriever.invoke(question)
context = "\n".join([d.page_content for d in docs])
messages = prompt.format_messages(context=context, question=question)
response = llm.invoke(messages)
return response.content
decision = build_rag_decision("Customer requests refund for duplicate card charge of $42")
print(decision)
- •
Execute the Stripe operation from the decision output
Once the model says “refund,” call Stripe directly. For a real system, parse JSON strictly and validate amount/customer/payment intent before hitting the API.
import json
def issue_refund(payment_intent_id: str, amount_cents: int):
refund = stripe.Refund.create(
payment_intent=payment_intent_id,
amount=amount_cents,
)
return refund
# Example decision payload from the model:
raw = '{"action":"refund","reason":"duplicate charge","amount_cents":4200}'
payload = json.loads(raw)
if payload["action"] == "refund":
refund = issue_refund("pi_123456789", payload["amount_cents"])
print(refund["id"], refund["status"])
- •
Wrap both pieces in one agent flow
In production, you want one orchestration layer that retrieves context, reasons about policy, and then calls Stripe only when allowed. LangChain’s tool calling pattern is fine here if you keep tools narrow and deterministic.
from langchain_core.tools import tool
@tool
def lookup_banking_policy(query: str) -> str:
docs = retriever.invoke(query)
return "\n".join([d.page_content for d in docs])
@tool
def create_stripe_refund(payment_intent_id: str, amount_cents: int) -> str:
refund = stripe.Refund.create(
payment_intent=payment_intent_id,
amount=amount_cents,
)
return f"refund_id={refund['id']}, status={refund['status']}"
Testing the Integration
Use test mode in Stripe and verify both retrieval and payment execution paths.
def test_flow():
question = "Can we refund a duplicate charge of $42?"
context_docs = retriever.invoke(question)
assert len(context_docs) > 0
# Replace with a real test PaymentIntent ID from Stripe test mode.
refund_result = stripe.Refund.create(
payment_intent="pi_test_123",
amount=4200,
)
print("Retrieved:", context_docs[0].page_content)
print("Refund:", refund_result["id"], refund_result["status"])
test_flow()
Expected output:
Retrieved: Refund requests over $500 require manual approval.
Refund: re_123456789 succeeded
Real-World Use Cases
- •
Payment support agent
- •Retrieves account/payment policy from your knowledge base.
- •Uses Stripe to look up invoices, confirm payment status, or issue refunds within policy limits.
- •
Collections assistant
- •Pulls delinquency rules and customer communication templates via RAG.
- •Calls Stripe invoice APIs to send reminders or reconcile overdue balances.
- •
Fraud review workflow
- •Retrieves internal escalation rules and risk thresholds.
- •Uses Stripe objects like charges, customers, and payment intents to assemble an investigation packet.
The main pattern is simple: let LangChain handle retrieval and reasoning, then let Stripe handle money movement. Keep those boundaries strict, validate every action before execution, and you get an agent that is useful without being reckless.
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