Skip to main content

इंस्टॉल करें

pip install l402kit langchain langchain-community

बुनियादी उपयोग

import os
from l402kit.langchain import L402Tool
from l402kit.wallets import BlinkWallet
from langchain.agents import AgentExecutor, create_react_agent
from langchain_openai import ChatOpenAI
from langchain import hub

# 1. Create the tool
tools = [
    L402Tool(
        wallet=BlinkWallet(
            os.environ["BLINK_API_KEY"],
            os.environ["BLINK_WALLET_ID"],
        ),
        budget_sats=1000,
    )
]

# 2. Wire it into a LangChain agent
llm = ChatOpenAI(model="gpt-4o")
prompt = hub.pull("hwchase17/react")
agent = create_react_agent(llm, tools, prompt)
agent_executor = AgentExecutor(agent=agent, tools=tools, verbose=True)

# 3. Run — the agent pays automatically when needed
result = agent_executor.invoke({
    "input": "What is the BTC price from https://api.example.com/btc-price?"
})
print(result["output"])

Alby के साथ

from l402kit.wallets import AlbyWallet

tools = [
    L402Tool(
        wallet=AlbyWallet(os.environ["ALBY_TOKEN"]),
        budget_sats=500,
    )
]

Tool संदर्भ

Constructor

L402Tool(
    wallet: L402Wallet,
    budget_sats: int | None = None,
    budget_per_domain: dict[str, int] | None = None,
    on_spend: Callable[[int, str], None] | None = None,
)
ParameterTypeDescription
walletL402WalletInvoice भुगतान करने के लिए उपयोग किया जाने वाला Wallet
budget_satsintइस session में खर्च करने योग्य अधिकतम sats
budget_per_domaindictप्रति-domain खर्च सीमाएं
on_spendcallableप्रत्येक भुगतान के बाद call किया जाता है

Tool schema (LLM द्वारा देखा गया)

name: "l402_fetch"
description: "Fetch data from an L402-protected API that requires a Lightning micropayment.
              Handles the payment automatically.
              Input: a URL (and optionally method/body).
              Output: the API response as text."

inputs:
  url:    string  — The URL to fetch
  method: string  — HTTP method: GET, POST, PUT, DELETE (default: GET)
  body:   string  — Request body as JSON string (for POST/PUT)

Methods

tool._run(url, method="GET", body=None)     # sync
await tool._arun(url, method="GET", body=None)  # async

tool.spending_report()  # → SpendingReport | None

Response format

Tool एक ऐसी string लौटाता है जिसे LLM सीधे पढ़ सकता है:
# Free endpoint
HTTP 200
{"price": 97500, "currency": "USD"}

# Paid endpoint (priceSats was in the 402 response)
[Paid 10 sats] HTTP 200
{"price": 97500, "currency": "USD"}

# Budget exceeded
[BLOCKED] Budget exceeded: need 50 sats but only 10 remaining (https://...)

# Network / wallet error
[ERROR] Connection refused

POST उदाहरण

result = agent_executor.invoke({
    "input": "Submit this query to https://api.example.com/search: {\"q\": \"bitcoin\"}"
})
# The agent calls l402_fetch with method=POST and body='{"q":"bitcoin"}'

Spending report

tool = L402Tool(wallet=wallet, budget_sats=1000)
# ... agent runs ...

report = tool.spending_report()
if report:
    print(f"Spent {report.total} sats across {len(report.transactions)} calls")
    for tx in report.transactions:
        print(f"  {tx['sats']} sats → {tx['url']}")

Custom agent frameworks

L402Tool एक langchain.tools.BaseTool subclass है — यह किसी भी ऐसे framework के साथ काम करता है जो LangChain tools स्वीकार करता है: LangGraph, CrewAI, AutoGen (adapter के माध्यम से), और अन्य।
# LangGraph example
from langgraph.prebuilt import create_react_agent

app = create_react_agent(llm, tools=[L402Tool(wallet=wallet, budget_sats=500)])
result = app.invoke({"messages": [("user", "fetch https://api.example.com/data")]})

Error handling

BudgetExceededError को internally पकड़ा जाता है — tool raise करने की बजाय एक [BLOCKED] string लौटाता है, ताकि agent इसे अपने reasoning loop में gracefully handle कर सके। अन्य सभी exceptions (network errors, wallet failures) को [ERROR] <message> के रूप में लौटाया जाता है। यदि आपको programmatic access की आवश्यकता है:
from l402kit import BudgetExceededError

class MyL402Tool(L402Tool):
    def _run(self, url, method="GET", body=None, run_manager=None):
        result = super()._run(url, method, body, run_manager)
        if result.startswith("[BLOCKED]"):
            raise BudgetExceededError(url, 0, 0)  # re-raise for outer handler
        return result

LangChain इंस्टॉल किए बिना

यदि langchain इंस्टॉल नहीं है, तो L402Tool को import करना module level पर सफल होता है (graceful fallback), लेकिन इसे instantiate करने पर यह raise करता है:
ImportError: langchain is required to use L402Tool.
Install it with: pip install langchain langchain-community