How to Integrate LangGraph for payments with Redis for RAG
If you’re building an AI agent that can answer questions from your knowledge base and also move money, you need hard boundaries between retrieval and execution. LangGraph gives you the control flow for payment workflows, while Redis gives you fast, persistent retrieval for RAG so the agent can fetch context before it decides whether a payment action is allowed.
This combo is useful when a support agent needs to look up policy docs, verify transaction context, and then trigger a payment step only after the right checks pass. You get stateful orchestration for payments and low-latency vector search for retrieval in one system.
Prerequisites
- •Python 3.10+
- •A LangGraph project set up with your payment workflow nodes
- •Redis 7+ running locally or via Redis Cloud
- •
redisPython package installed - •
langgraphinstalled - •Your embedding model configured for RAG
- •Payment API credentials or sandbox keys for the downstream payment service
- •Environment variables set:
- •
REDIS_URL - •
PAYMENTS_API_KEY - •
PAYMENTS_API_BASE_URL
- •
Integration Steps
- •Install the dependencies and wire your clients together.
pip install langgraph redis openai python-dotenv
import os
from dotenv import load_dotenv
from redis import Redis
load_dotenv()
redis_client = Redis.from_url(os.environ["REDIS_URL"], decode_responses=True)
print(redis_client.ping())
- •Store your RAG documents in Redis using vector-aware keys.
For production, use Redis Stack or Redis Cloud with vector search enabled. The pattern below stores chunked content plus metadata that your agent can retrieve before deciding whether a payment action is valid.
import json
import uuid
def store_doc(redis_client, text: str, source: str, doc_type: str):
doc_id = str(uuid.uuid4())
payload = {
"id": doc_id,
"text": text,
"source": source,
"doc_type": doc_type,
}
redis_client.hset(f"rag:doc:{doc_id}", mapping=payload)
redis_client.sadd(f"rag:index:{doc_type}", doc_id)
return doc_id
policy_id = store_doc(
redis_client,
text="Refunds above $500 require supervisor approval.",
source="payments-policy.pdf",
doc_type="policy",
)
print(policy_id)
- •Build a retrieval function that LangGraph nodes can call.
This is where Redis becomes the RAG layer for your agent. In a real setup, replace the simple scan with FT.SEARCH against a vector index; the interface stays the same for downstream graph nodes.
from typing import List, Dict
def retrieve_context(redis_client, query: str) -> List[Dict]:
# Replace this with RediSearch vector query in production.
results = []
for key in redis_client.scan_iter(match="rag:doc:*", count=100):
doc = redis_client.hgetall(key)
if query.lower() in doc.get("text", "").lower():
results.append(doc)
return results[:5]
context = retrieve_context(redis_client, "refund approval")
print(context)
- •Create a LangGraph workflow that gates payment execution on retrieved policy context.
Use LangGraph’s StateGraph to orchestrate retrieval first, then payment execution only if policy conditions are satisfied. This keeps your agent from calling payments blindly.
from typing import TypedDict, Annotated, List
from langgraph.graph import StateGraph, END
class AgentState(TypedDict):
user_query: str
retrieved_docs: List[dict]
approved: bool
payment_result: dict | None
def retrieve_node(state: AgentState):
docs = retrieve_context(redis_client, state["user_query"])
return {"retrieved_docs": docs}
def approve_node(state: AgentState):
text_blob = " ".join(doc["text"] for doc in state["retrieved_docs"])
approved = "supervisor approval" not in text_blob.lower()
return {"approved": approved}
def payment_node(state: AgentState):
# Replace with your actual payments SDK call.
# Example shape mirrors common API client usage.
result = {
"status": "submitted",
"amount": 250,
"currency": "USD",
"reference": "pay_12345",
}
return {"payment_result": result}
graph = StateGraph(AgentState)
graph.add_node("retrieve", retrieve_node)
graph.add_node("approve", approve_node)
graph.add_node("payment", payment_node)
graph.set_entry_point("retrieve")
graph.add_edge("retrieve", "approve")
def route_after_approve(state: AgentState):
return "payment" if state["approved"] else END
graph.add_conditional_edges("approve", route_after_approve)
graph.add_edge("payment", END)
app = graph.compile()
- •Call the graph from your application and persist execution state in Redis.
This gives you auditability and lets you rehydrate sessions later. Store each run result under a request key so support teams can inspect what context led to a payment decision.
run_state = app.invoke(
{
"user_query": "Can I refund this customer?",
"retrieved_docs": [],
"approved": False,
"payment_result": None,
}
)
redis_client.set(
f"agent:run:{uuid.uuid4()}",
json.dumps(run_state),
)
print(run_state)
Testing the Integration
Run a simple end-to-end check that verifies retrieval happens before payment execution.
test_state = app.invoke(
{
"user_query": "refund approval",
"retrieved_docs": [],
"approved": False,
"payment_result": None,
}
)
print("Approved:", test_state["approved"])
print("Payment Result:", test_state["payment_result"])
print("Docs Found:", len(test_state["retrieved_docs"]))
Expected output:
Approved: False
Payment Result: None
Docs Found: 1
If you change the stored policy text so it does not mention supervisor approval, the graph should route to payment and return a populated payment_result.
Real-World Use Cases
- •
Support-driven refunds
- •Retrieve refund policy from Redis RAG.
- •Use LangGraph to enforce approval rules.
- •Trigger a refund only when policy and transaction context match.
- •
Claims payout assistants
- •Pull claim rules, deductible thresholds, and fraud notes from Redis.
- •Use LangGraph to branch into manual review or payout execution.
- •Keep an audit trail of every decision path.
- •
Treasury ops copilots
- •Answer internal questions about transfer limits and beneficiary rules.
- •Gate wire initiation behind retrieved compliance context.
- •Persist each run in Redis for traceability and replay.
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