Introduction
Reinforcement Learning (RL) is a powerful tool for optimizing digital wallet onboarding incentives, but it comes with an inherent risk: exploration. To learn, an RL agent must try new actions. In a video game, a bad action means losing a life. In fintech, a bad action could mean offering a $500 bonus to a fraudulent user or violating regulatory caps on inducements.
The question every enterprise architect asks is: How do we allow the model to learn without blowing up the budget or breaking the law?
The answer lies in Constrained RL and Architectural Guardrails. We cannot trust the LLM or the RL agent to be safe on its own. Safety must be enforced structurally within the orchestration layer. This article demonstrates how to build a Safe Dynamic Pricing Engine for wallet creation using LangGraph. We will implement action masking, compliance-aware retrieval, and hard-bound verification to ensure that exploration never crosses into unsafe territory.
Disclaimer: This POC uses simulated data and simplified Q-Learning for educational purposes. Always consult legal and risk teams before deploying financial incentive algorithms.
The Danger of Unconstrained Exploration
In standard Q-Learning, an agent uses an epsilon-greedy strategy to explore. If ϵ=0.1ϵ=0.1, 10% of the time it picks a random action. In our wallet context, "random" could mean selecting Large_Bonus for a High_Risk_User. Without guardrails, the agent only learns this was bad after the money is lost. We need to prevent the unsafe action from ever being executed.
Safety Architecture: The Guardrail Pattern
Our safety strategy operates on three levels:
Pre-Computation (RAG): Retrieve hard constraints (e.g., "Max bonus for students is $10") before the RL agent acts.
Action Masking: Filter the RL agent’s available action space based on retrieved constraints. The agent literally cannot choose an illegal action.
Post-Verification (Guardrail Node): A deterministic code-based check that validates the final output against business rules before returning it to the user. If validation fails, it falls back to a safe default.
Real-Time Use Case: Wallet Funding Incentive Optimization
Scenario: A new user signs up for a digital wallet. The system must decide on a funding incentive. Safety Constraints:
Students: Max $10 bonus.
High-Risk KYC Score: No cash bonuses allowed.
Global Cap: Never exceed $50 regardless of segment.
System Behavior:
RAG Agent retrieves the specific cap for the user's segment.
RL Agent receives a masked action space (e.g., if Student,
Large_Bonusis removed from options).Guardrail Node verifies the selected action. If the RL agent somehow hallucinated or the mask failed, the node overrides it with
No_Incentive.

Technology Stack Overview
Backend: Python 3.12, FastAPI, Uvicorn
Orchestration: LangGraph (for stateful, cyclic safety workflows)
RAG: LangChain, ChromaDB, HuggingFace Embeddings
RL: Custom Q-Learning with Action Masking (NumPy)
Memory: SQLite via LangGraph Checkpointer
Frontend: React, Vite, Tailwind CSS
Project Architecture
safe-wallet-pricing/
├── backend/
│ ├── app/
│ │ ├── main.py
│ │ ├── config.py
│ │ ├── models/
│ │ │ └── state.py
│ │ ├── agents/
│ │ │ ├── compliance_retriever.py
│ │ │ ├── safe_rl_agent.py
│ │ │ └── safety_guardrail.py
│ │ ├── graph/
│ │ │ └── workflow.py
│ │ └── rag/
│ │ └── ingest.py
│ └── requirements.txt
├── frontend/
│ ├── src/
│ │ ├── App.jsx
│ │ └── components/
│ │ └── SafePricingDashboard.jsx
│ └── package.json
└── README.md
Step-by-Step POC Implementation
Backend Setup and Configuration
backend/requirements.txt
fastapi
uvicorn
langgraph
langchain
langchain-community
chromadb
sentence-transformers
numpy
python-dotenv
pydantic
backend/app/config.py
import os
from dotenv import load_dotenv
load_dotenv()
class Settings:
CHROMA_PATH = "./chroma_db"
LEARNING_RATE = 0.1
DISCOUNT_FACTOR = 0.9
EXPLORATION_RATE = 0.15
# Hard safety bounds that override everything
ABSOLUTE_MAX_BONUS = 50.0
settings = Settings()
Defining the LangGraph State with Safety Bounds
backend/app/models/state.py
from typing import TypedDict, List, Optional, Annotated
from langgraph.graph import add_messages
class WalletState(TypedDict):
messages: Annotated[list, add_messages]
user_id: str
user_profile: dict
# Safety-specific fields
compliance_constraints: dict
allowed_actions: List[str]
# RL fields
state_key: str
selected_action: str
reward: float
q_table_updated: bool
# Output fields
final_offer: str
safety_override: bool
RAG Component: Compliance & Risk Policy Retrieval
backend/app/rag/ingest.py
from langchain_core.documents import Document
from langchain_community.vectorstores import Chroma
from langchain_community.embeddings import HuggingFaceEmbeddings
from langchain_text_splitters import RecursiveCharacterTextSplitter
def get_compliance_docs():
return [
Document(
page_content="Student Segment: Maximum cash incentive capped at $10. Fee waivers permitted.",
metadata={"segment": "Student", "max_cash": 10, "allowed_types": ["Small_Bonus", "Fee_Waiver", "No_Incentive"]}
),
Document(
page_content="Professional Segment: Maximum cash incentive capped at $50. Requires income verification.",
metadata={"segment": "Professional", "max_cash": 50, "allowed_types": ["Small_Bonus", "Large_Bonus", "Fee_Waiver", "No_Incentive"]}
),
Document(
page_content="High Risk KYC: NO cash incentives allowed. Only fee waivers or gamification.",
metadata={"segment": "High_Risk", "max_cash": 0, "allowed_types": ["Fee_Waiver", "No_Incentive"]}
)
]
def ingest_data():
docs = get_compliance_docs()
splitter = RecursiveCharacterTextSplitter(chunk_size=500, chunk_overlap=50)
split_docs = splitter.split_documents(docs)
embeddings = HuggingFaceEmbeddings(model_name="all-MiniLM-L6-v2")
vector_store = Chroma.from_documents(
documents=split_docs,
embedding=embeddings,
persist_directory="./chroma_db"
)
print("Compliance policies ingested.")
return vector_store
The RL Agent with Action Masking
This is the core safety mechanism. The agent does not explore the full space; it explores only the safe subspace.
backend/app/agents/safe_rl_agent.py
import numpy as np
import random
from app.config import settings
ALL_ACTIONS = ["No_Incentive", "Small_Bonus", "Large_Bonus", "Fee_Waiver"]
class SafeQLearningAgent:
def __init__(self):
self.q_table = {}
def get_state_key(self, profile):
return f"{profile.get('type', 'Unknown')}_{profile.get('risk', 'Low')}"
def choose_action(self, state_key, allowed_actions):
if state_key not in self.q_table:
self.q_table[state_key] = np.zeros(len(ALL_ACTIONS))
# SAFETY MECHANISM: Action Masking
# Create a list of valid indices based on allowed_actions
valid_indices = [i for i, a in enumerate(ALL_ACTIONS) if a in allowed_actions]
if not valid_indices:
return "No_Incentive" # Ultimate fallback
if random.uniform(0, 1) < settings.EXPLORATION_RATE:
# Explore ONLY within safe bounds
idx = random.choice(valid_indices)
else:
# Exploit ONLY within safe bounds
# Set invalid actions to -inf so argmax ignores them
masked_q = np.full(len(ALL_ACTIONS), -np.inf)
for i in valid_indices:
masked_q[i] = self.q_table[state_key][i]
idx = np.argmax(masked_q)
return ALL_ACTIONS[idx]
def learn(self, state_key, action, reward):
if state_key not in self.q_table:
self.q_table[state_key] = np.zeros(len(ALL_ACTIONS))
idx = ALL_ACTIONS.index(action)
old_value = self.q_table[state_key][idx]
next_max = np.max(self.q_table[state_key])
new_value = old_value + settings.LEARNING_RATE * (reward + settings.DISCOUNT_FACTOR * next_max - old_value)
self.q_table[state_key][idx] = new_value
rl_agent = SafeQLearningAgent()
def safe_rl_node(state):
state_key = rl_agent.get_state_key(state["user_profile"])
state["state_key"] = state_key
# Learn from previous interaction
if state.get("reward") is not None and state.get("prev_action"):
rl_agent.learn(state_key, state["prev_action"], state["reward"])
state["q_table_updated"] = True
# Choose action using MASKED exploration
allowed = state.get("allowed_actions", ALL_ACTIONS)
action = rl_agent.choose_action(state_key, allowed)
state["selected_action"] = action
state["prev_action"] = action
return state

Join the conversation! Your thoughts help the community grow.