Start here: need to register a service and create a plan first? Follow the
5-minute setup.
Runnable tutorial
langchain-paid-agent-py — a deliberately minimal LangChain + LangGraph agent
with a single tool gated by @requires_payment. Clone, fill in .env, run
poetry run buyer to see the full discovery → token-acquisition → settlement
flow in five numbered steps. The cleanest starting point if you’d rather read
working code than docs.
Both use the same Nevermined plan, credits, and settlement flow — choose whichever fits your deployment model.
Installation
- TypeScript
- Python
The
@nevermined-io/payments/langchain sub-path export provides the requiresPayment() wrapper.
For the HTTP server approach, also install express.Approach 1: Tool Decorator / Wrapper
x402 Payment Flow (decorator)
Quick Start
- TypeScript
- Python
In LangChain.js,
requiresPayment() is a higher-order function that wraps the tool implementation:Invoking with payment
- TypeScript
- Python
LLM-driven tool calling
- TypeScript
- Python
LangGraph ReAct agent
The same payment-protected tools work with LangGraph’screate_react_agent. The simple case — buyer already holds a token — just threads it through configurable:
- TypeScript
- Python
Discovery-first flow with createPaidReactAgent
If the buyer doesn’t know the plan id / scheme / provider up front, the x402 way is to invoke the agent without a token, let the protected tool raise PaymentRequiredError, and read the requirements off the exception. By default LangGraph’s ToolNode would catch that exception and stringify it into a ToolMessage for the LLM — losing the X402PaymentRequired payload. Both SDKs ship a paid-agent helper for exactly this — createPaidReactAgent (TypeScript) / create_paid_react_agent (Python) — that builds the underlying ToolNode with handleToolErrors: false / handle_tool_errors=False, so the exception propagates to agent.invoke()’s caller with the payload intact.
- TypeScript
- Python
Create the delegation that backs the payment signature first (with
createDelegation), then pass its delegationId in the token’s
delegationConfig. This applies to both card-delegation and crypto
(nvm:erc4337) plans. Passing creation fields inline instead of a
delegationId is deprecated and emits a runtime warning — see the x402
Protocol module reference (TypeScript ·
Python) for the full token-options
surface. This discovery flow covers Stripe and Braintree. For Visa-priced
plans, createDelegation from the SDK is rejected (BCK.VISA.0014) — create
the Visa delegation in the Nevermined app and reuse its delegationId here.createPaidReactAgent is async in TypeScript — it awaits the lazy
@langchain/langgraph import so the dependency stays optional. Install
LangGraph yourself (pnpm add @langchain/langgraph) to use it.Reading the settlement receipt
After a successful agent call, the buyer can read the settlement receipt — credits redeemed, remaining balance, transaction hash, network, payer — vialastSettlement() (TypeScript) / last_settlement() (Python). LangGraph copies configurable per node, so the in-place payment_settlement write is invisible to the outer scope; the accessor reads it from a module-level slot instead.
- TypeScript
- Python
Trace payments in LangSmith
Once payment protection is wired up, you can have every paid tool call surface as structured spans in LangSmith — no code changes required, just two env vars and an optional dependency. Both SDKs emit the identicalnvm:verify / nvm:settlement span shape (the cross-SDK observability-spans-v1 contract), so a single trace can be correlated across a TypeScript buyer and a Python seller — e.g. filter on nvm.tx_hash.
Install the optional dependency:
- TypeScript
- Python
langsmith is an optional peer dependency — the requiresPayment wrapper emits the spans automatically when it is installed and tracing is enabled.nvm.* metadata for audit + reconciliation:
The same
nvm.* metadata is also attached to the parent tool span so cmd-F searches in the LangSmith UI land on either level.
Failed discovery probes are first-class too. When the buyer’s first agent.invoke() runs without a payment_token (the discovery-first flow), the nvm:verify span still opens, carries the static nvm.plan_ids / nvm.scheme / nvm.network, and is marked failed by the raised PaymentRequiredError. That gives you “which plan was the probe against?” filterability instead of an opaque LangChain crash.
If a span failure ever occurs during metadata building or attachment, observability is silently dropped — the payment flow itself is never interrupted. Settlement receipts persist (via lastSettlement() in TypeScript / last_settlement() in Python) regardless of whether the span emit succeeded.
For the full module reference, see the Python LangChain module reference. The TypeScript helper surface (verifySpan, settlementSpan, abbreviateToken, addMetadata, redactMetadataKeys, activeRunTree, plus buildVerifyMetadata / buildSettleMetadata for manual use outside the requiresPayment decorator) is exported from @nevermined-io/payments/langsmith — JSDoc on each helper documents the contract until the next update-docs.yml sync mirrors a dedicated TS api-reference page.
Dynamic Credits
The
credits argument is sent to the facilitator as max_amount. The amount
actually redeemed depends on the plan’s server-side credit config:
fixed plans (where plan.credits.minAmount == plan.credits.maxAmount)
always burn plan.credits.maxAmount and ignore the supplied value (per
nvm-monorepo#1568);
range plans clamp the value into [minAmount, maxAmount]. If you want
predictable per-call cost, configure the plan as fixed.- TypeScript
- Python
Three patterns for credit calculation:The credits function receives
{ args, result } after tool execution.Approach 2: HTTP Server with Payment Middleware
For serving the agent over HTTP, use payment middleware on your framework. Payment is handled at the HTTP layer — tools are plain functions with no decorators or payment config.x402 Payment Flow (HTTP)
Server: LangChain
- TypeScript (Express)
- Python (FastAPI)
Server: LangGraph
Replace the tool-call loop with LangGraph’screate_react_agent:
- TypeScript
- Python
Client: Full x402 HTTP Flow
- TypeScript
- Python
x402 HTTP Headers
The settlement receipt (
payment-response) contains:
Decorator Configuration
With Agent ID
- TypeScript
- Python
Multiple Plans (Python only)
Scheme and Network
- TypeScript
- Python
The decorator/wrapper automatically detects the payment scheme from plan metadata.
Plans with fiat pricing (
isCrypto: false) use nvm:card-delegation (Stripe).
No code changes are needed on the agent side.Complete Examples
Working seller/buyer agents with LangGraph — includes both Python and TypeScript variants:- TypeScript
- Python
- seller-simple-agent/ts — Seller with
paymentMiddleware+requiresPaymentdemo - buyer-simple-agent/ts — Buyer CLI agent with x402 token generation
src/server.ts/src/agent.ts— LangGraphcreateReactAgentwith payment-protected toolssrc/demo.ts—requiresPaymentwrapper demo (seller only)src/client.ts— HTTP client with full x402 payment flow
Environment Variables
Next Steps
Express Middleware (TS)
Deep dive into paymentMiddleware for Express
FastAPI Middleware (Python)
Deep dive into PaymentMiddleware for FastAPI
x402 Protocol
Deep dive into x402 payment flows
Payment Models
Configure credits, subscriptions, and dynamic pricing