Skip to main content

LangChain Route402 Integration

Enable your LangChain agents to make autonomous USDC payments on Base blockchain.

Installation

pip install langchain-route402

Quick Start

from langchain_route402 import Route402Toolkit
from langchain.agents import AgentExecutor, create_react_agent
from langchain_openai import ChatOpenAI
from langchain import hub

# Get Route402 API key from https://route402.com
toolkit = Route402Toolkit(api_key="apk_your_key_here")

# Create agent with payment capabilities
llm = ChatOpenAI(temperature=0)
prompt = hub.pull("hwchase17/react")
agent = create_react_agent(llm, toolkit.get_tools(), prompt)
agent_executor = AgentExecutor(agent=agent, tools=toolkit.get_tools(), verbose=True)

# Agent can now make payments autonomously
result = agent_executor.invoke({
    "input": "Pay 0.05 USDC to 0x742d35Cc6634C0532925a3b844Bc9e7595f0bEb for the premium signal"
})

Features

  • ✅ Autonomous Payments: Agents can send USDC without human intervention
  • ✅ Fast: Payments confirmed in ~25 seconds
  • ✅ Reliable: 0% failure rate (CONFIRMED status only)
  • ✅ Low Cost: 0.5% fee (50 basis points)
  • ✅ Base Blockchain: Native USDC on Base L2 (low gas fees)

Use Cases

1. AI Trading Bot Buying Signals

from langchain_route402 import Route402PaymentTool
from langchain_openai import ChatOpenAI
from langchain.agents import initialize_agent

# Initialize tool
payment_tool = Route402PaymentTool(api_key="apk_your_key")

# Create agent
llm = ChatOpenAI(temperature=0)
agent = initialize_agent(
    tools=[payment_tool],
    llm=llm,
    agent="zero-shot-react-description",
    verbose=True
)

# Agent decides when to buy signals
agent.run(
    "Monitor the market. If BTC drops below $95k, "
    "buy the premium signal from 0x742d35... for 0.05 USDC"
)

2. Research Agent Paying for Data

# Agent autonomously pays for premium data when needed
result = agent_executor.invoke({
    "input": (
        "Research the latest AI developments. "
        "If you need premium research papers, pay 0.10 USDC to "
        "the academic API at 0x55ee389d..."
    )
})

3. Multi-Agent Marketplace

from langchain.agents import Agent

# Seller agent
seller = Agent(
    tools=[Route402CheckPaymentTool(api_key="apk_seller")],
    llm=llm
)

# Buyer agent
buyer = Agent(
    tools=[Route402PaymentTool(api_key="apk_buyer")],
    llm=llm
)

# Autonomous negotiation + payment
buyer.run("Negotiate with seller, then pay for the service if price < 1 USDC")

Tools

route402_payment

Make USDC payments on Base blockchain.

Inputs:

  • seller (str): Ethereum address receiving payment (0x...)
  • amount (str): Amount in USDC (e.g., "0.05" = 5 cents)
  • reference (str, optional): Tracking reference

Returns:

  • Payment ID
  • Transaction hash
  • Confirmation status

Example:

from langchain_route402 import Route402PaymentTool

tool = Route402PaymentTool(api_key="apk_your_key")
result = tool._run(
    seller="0x742d35Cc6634C0532925a3b844Bc9e7595f0bEb",
    amount="0.05",
    reference="signal-purchase-123"
)
print(result)
# ✅ Payment created successfully!
# Payment ID: pay_abc123
# Amount: 0.05 USDC
# Fee: 0.00025 USDC
# Net to seller: 0.04975 USDC
# Status: CONFIRMED
# ✅ Payment confirmed on blockchain

route402_check_payment

Check payment status by ID.

Inputs:

  • payment_id (str): Payment ID from route402_payment

Returns:

  • Payment status
  • Transaction hash
  • Confirmation time

Example:

from langchain_route402 import Route402CheckPaymentTool

tool = Route402CheckPaymentTool(api_key="apk_your_key")
result = tool._run(payment_id="pay_abc123")
print(result)
# Payment pay_abc123
# Status: CONFIRMED
# Amount: 0.05 USDC
# Seller: 0x742d35Cc6634C0532925a3b844Bc9e7595f0bEb
# TX: https://basescan.org/tx/0x...
# ✅ Confirmed at 2025-01-15 10:00:25

Integration with Existing Agents

Add to OpenAI Functions Agent

from langchain.agents import create_openai_functions_agent
from langchain_route402 import Route402Toolkit

toolkit = Route402Toolkit(api_key="apk_your_key")

agent = create_openai_functions_agent(
    llm=ChatOpenAI(model="gpt-4", temperature=0),
    tools=toolkit.get_tools(),
    prompt=prompt
)

Add to ReAct Agent

from langchain.agents import create_react_agent
from langchain_route402 import Route402Toolkit

toolkit = Route402Toolkit(api_key="apk_your_key")

agent = create_react_agent(
    llm=ChatOpenAI(temperature=0),
    tools=toolkit.get_tools(),
    prompt=prompt
)

Add to Conversational Agent

from langchain.agents import create_conversational_agent
from langchain_route402 import Route402Toolkit

toolkit = Route402Toolkit(api_key="apk_your_key")

agent = create_conversational_agent(
    llm=ChatOpenAI(temperature=0),
    tools=toolkit.get_tools(),
    prompt=prompt
)

Budget Control

Control agent spending with custom logic:

class BudgetControlledAgent:
    def __init__(self, api_key: str, daily_limit: float = 10.0):
        self.toolkit = Route402Toolkit(api_key=api_key)
        self.daily_limit = daily_limit
        self.spent_today = 0.0

    def can_spend(self, amount: float) -> bool:
        """Check if agent can spend this amount"""
        return (self.spent_today + amount) <= self.daily_limit

    def execute_payment(self, seller: str, amount: str, reference: str = None):
        """Execute payment with budget check"""
        amount_float = float(amount)

        if not self.can_spend(amount_float):
            return f"❌ Budget exceeded. Spent: ${self.spent_today}, Limit: ${self.daily_limit}"

        tool = Route402PaymentTool(api_key=self.toolkit.api_key)
        result = tool._run(seller=seller, amount=amount, reference=reference)

        if "✅ Payment created" in result:
            self.spent_today += amount_float

        return result

# Usage
agent = BudgetControlledAgent(api_key="apk_your_key", daily_limit=5.0)
agent.execute_payment(seller="0x742d35...", amount="0.05")

Error Handling

from route402.exceptions import APIError, ValidationError, PaymentError

try:
    result = payment_tool._run(
        seller="0x742d35Cc6634C0532925a3b844Bc9e7595f0bEb",
        amount="0.05"
    )
except ValidationError as e:
    print(f"Invalid input: {e}")
except APIError as e:
    print(f"API error: {e.message} (status {e.status_code})")
except PaymentError as e:
    print(f"Payment failed: {e}")

Requirements

  • Python 3.8+
  • route402>=0.1.0
  • langchain>=0.1.0
  • langchain-core>=0.1.0

Get Route402 API Key

  1. Visit route402.com
  2. Connect your wallet
  3. Generate API key
  4. Fund your wallet with USDC on Base

License

MIT

Metadata

Release files for langchain-route402 0.1.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for langchain-route402 0.1.0
File Size Uploaded
langchain_route402-0.1.0.tar.gz 10.4 kB Details

Built distribution (wheel)

Table of built distributions (wheels) for langchain-route402 0.1.0
File Interpreter ABI Platform
langchain_route402-0.1.0-py3-none-any.whl Python 3 none any Details

Total release size: 17.1 kB

Release files / langchain_route402-0.1.0.tar.gz

Download URL langchain_route402-0.1.0.tar.gz
Size 10.4 kB
Tags Source
SHA-256 checksum
How to use checksums
5bf8664bf6cb9e8e7e4688d7ec9ce73cf2baa3b737e1a197927f3c8f36e1daa4
BLAKE2b-256 checksum
How to use checksums
6ce4f1d7bf14749024de34f6ea73a29c439e687f7bfeb8433eaf86ef284bc138
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/6.2.0 CPython/3.13.2

Release files / langchain_route402-0.1.0-py3-none-any.whl

Download URL langchain_route402-0.1.0-py3-none-any.whl
Size 6.7 kB
Tags Python 3
SHA-256 checksum
How to use checksums
4f96fd8d4ad7afd755b4619db344afc1732a875a239bfcabaf840154a1ed180c
BLAKE2b-256 checksum
How to use checksums
0d06f40f2dcb22630057382c2eedd0465d855d7e4f6d77328483ba0351aedc7c
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/6.2.0 CPython/3.13.2

Release history Release notifications | RSS feed

This release

0.1.0 This release

2 release files

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page