How to Integrate FastAPI for payments with LangChain for multi-agent systems
Combining FastAPI for payments with LangChain gives you a clean split between money movement and agent orchestration. FastAPI handles the payment API surface, while LangChain coordinates multiple agents that can decide when to charge, verify, retry, or escalate a transaction. That pattern shows up in billing assistants, subscription ops, invoice automation, and payment support flows.
Prerequisites
- •Python 3.10+
- •
fastapi,uvicorn,pydantic - •
langchain,langchain-openaior another LLM provider - •A payment provider SDK, for example:
- •Stripe:
stripe - •PayPal: their REST SDK or direct HTTP calls
- •Stripe:
- •Environment variables configured:
- •
OPENAI_API_KEY - •
STRIPE_SECRET_KEYor your provider key
- •
- •A running FastAPI app with a payments route
- •Basic familiarity with async Python
Integration Steps
- •Set up the payment service in FastAPI.
Use FastAPI as the execution layer for payment actions. Keep the API small: create payment intent, confirm payment, refund payment, and fetch status.
from fastapi import FastAPI, HTTPException
from pydantic import BaseModel
import stripe
import os
app = FastAPI()
stripe.api_key = os.getenv("STRIPE_SECRET_KEY")
class PaymentRequest(BaseModel):
amount: int
currency: str = "usd"
customer_email: str
@app.post("/payments/create")
async def create_payment(req: PaymentRequest):
try:
intent = stripe.PaymentIntent.create(
amount=req.amount,
currency=req.currency,
receipt_email=req.customer_email,
automatic_payment_methods={"enabled": True},
)
return {"payment_intent_id": intent.id, "client_secret": intent.client_secret}
except stripe.error.StripeError as e:
raise HTTPException(status_code=400, detail=str(e))
This keeps payment logic isolated. LangChain should not talk to Stripe directly unless you want it to; it should call your API layer.
- •Expose payment actions as tools for LangChain agents.
LangChain agents work best when they have explicit tools. Wrap your FastAPI endpoints as callable tools so an agent can decide which payment operation to run.
import requests
from langchain_core.tools import tool
PAYMENTS_BASE_URL = "http://localhost:8000"
@tool
def create_payment_tool(amount: int, currency: str, customer_email: str) -> dict:
"""Create a payment intent through the payments API."""
response = requests.post(
f"{PAYMENTS_BASE_URL}/payments/create",
json={
"amount": amount,
"currency": currency,
"customer_email": customer_email,
},
timeout=10,
)
response.raise_for_status()
return response.json()
This is the key boundary. The tool is what the agent sees; FastAPI remains the source of truth for transaction handling.
- •Build a multi-agent workflow in LangChain.
For multi-agent systems, split responsibilities. One agent can validate billing context, another can decide whether to initiate payment, and a third can summarize outcomes for logs or customer support.
from langchain_openai import ChatOpenAI
from langchain.agents import initialize_agent, AgentType
llm = ChatOpenAI(model="gpt-4o-mini", temperature=0)
billing_agent = initialize_agent(
tools=[create_payment_tool],
llm=llm,
agent=AgentType.ZERO_SHOT_REACT_DESCRIPTION,
verbose=True,
)
A practical setup is to keep one agent focused on policy and another on execution. If you need stricter control, use a router pattern where only one coordinator agent can invoke payment tools.
- •Add an orchestrator that decides when to charge.
In production, don’t let the model freely initiate charges from raw user text. Add a deterministic gate before any tool call. For example, require an approved order ID and verified amount from your business rules engine.
from pydantic import BaseModel
class ChargeDecision(BaseModel):
approved: bool
reason: str
def should_charge(order_status: str, fraud_check_passed: bool) -> ChargeDecision:
if order_status == "ready_to_bill" and fraud_check_passed:
return ChargeDecision(approved=True, reason="Order ready and fraud check passed")
return ChargeDecision(approved=False, reason="Billing blocked by policy")
def process_order(order_status: str, fraud_check_passed: bool):
decision = should_charge(order_status, fraud_check_passed)
if not decision.approved:
return {"status": "blocked", "reason": decision.reason}
result = billing_agent.invoke(
f"Create a payment for order billing amount 5000 cents in usd for customer billing@acme.com"
)
return {"status": "charged", "result": result}
This pattern matters in financial systems. Let policy decide eligibility; let the agent handle coordination and messaging.
- •Wire the FastAPI endpoint to trigger the LangChain workflow.
Your API becomes the entry point for external systems such as checkout services or CRM workflows. The endpoint receives business context and delegates to the orchestrator.
from fastapi import Body
@app.post("/orders/charge")
async def charge_order(payload: dict = Body(...)):
order_status = payload.get("order_status", "")
fraud_check_passed = payload.get("fraud_check_passed", False)
outcome = process_order(order_status, fraud_check_passed)
return outcome
This gives you a clean integration surface. External systems call FastAPI; FastAPI applies business rules; LangChain coordinates agent behavior only when needed.
Testing the Integration
Run FastAPI:
uvicorn main:app --reload --port 8000
Then test with a request:
import requests
response = requests.post(
"http://localhost:8000/orders/charge",
json={
"order_status": "ready_to_bill",
"fraud_check_passed": True,
},
)
print(response.status_code)
print(response.json())
Expected output:
200
{
"status": "charged",
"result": {
...
}
}
If the order is not eligible:
200
{
"status": "blocked",
"reason": "Billing blocked by policy"
}
Real-World Use Cases
- •Payment support agents that can look up failed charges, retry billing after policy checks, and generate customer-facing explanations.
- •Subscription operations systems where one agent validates plan changes and another triggers invoice creation or proration through your payments API.
- •Invoice approval workflows where an AI coordinator routes high-value invoices to human review before any charge is created.
The main design rule is simple: keep money movement inside FastAPI endpoints and use LangChain for orchestration around those endpoints. That separation makes your system testable, auditable, and much easier to secure in production.
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