langchain-route402 0.1.0
LangChain integration for Route402 - USDC payments for AI agents
License: MIT
Requires Python: >=3.8
Keywords: agents, ai, crypto, langchain, payments, route402, usdc

# LangChain Route402 Integration

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

## Installation

```bash
pip install langchain-route402
```

## Quick Start

```python
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

```python
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

```python
# 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

```python
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:**
```python
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:**
```python
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

```python
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

```python
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

```python
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:

```python
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

```python
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](https://route402.com)
2. Connect your wallet
3. Generate API key
4. Fund your wallet with USDC on Base

## Links

- **Website:** https://route402.com
- **Documentation:** https://docs.route402.com
- **API Reference:** https://docs.route402.com/api
- **Base SDK:** https://pypi.org/project/route402/
- **GitHub:** https://github.com/route402/route402
- **Support:** hello@route402.com

## License

MIT