l402sdk-langchain 0.1.0__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- l402sdk_langchain-0.1.0/.gitignore +48 -0
- l402sdk_langchain-0.1.0/CHANGELOG.md +17 -0
- l402sdk_langchain-0.1.0/PKG-INFO +174 -0
- l402sdk_langchain-0.1.0/README.md +144 -0
- l402sdk_langchain-0.1.0/pyproject.toml +50 -0
- l402sdk_langchain-0.1.0/src/l402_langchain/__init__.py +38 -0
- l402sdk_langchain-0.1.0/src/l402_langchain/callbacks.py +161 -0
- l402sdk_langchain-0.1.0/src/l402_langchain/config.py +165 -0
- l402sdk_langchain-0.1.0/src/l402_langchain/tools.py +178 -0
- l402sdk_langchain-0.1.0/tests/conftest.py +34 -0
- l402sdk_langchain-0.1.0/tests/test_callbacks.py +140 -0
- l402sdk_langchain-0.1.0/tests/test_config.py +111 -0
- l402sdk_langchain-0.1.0/tests/test_tools.py +49 -0
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
/target
|
|
2
|
+
Cargo.lock
|
|
3
|
+
**/*.rs.bk
|
|
4
|
+
*.pdb
|
|
5
|
+
.idea/
|
|
6
|
+
.vscode/
|
|
7
|
+
*.swp
|
|
8
|
+
*.swo
|
|
9
|
+
*~
|
|
10
|
+
.DS_Store
|
|
11
|
+
Thumbs.db
|
|
12
|
+
PROJECT.md
|
|
13
|
+
|
|
14
|
+
# Python
|
|
15
|
+
.venv/
|
|
16
|
+
__pycache__/
|
|
17
|
+
*.pyc
|
|
18
|
+
*.pyo
|
|
19
|
+
*.so
|
|
20
|
+
*.egg-info/
|
|
21
|
+
dist/
|
|
22
|
+
*.whl
|
|
23
|
+
.pytest_cache/
|
|
24
|
+
|
|
25
|
+
# Go bindings (built from CI)
|
|
26
|
+
bindings/l402-go/lib/
|
|
27
|
+
|
|
28
|
+
# WASM (built from wasm-pack)
|
|
29
|
+
crates/l402-wasm/pkg/
|
|
30
|
+
|
|
31
|
+
# TypeScript packages
|
|
32
|
+
packages/*/node_modules/
|
|
33
|
+
packages/*/dist/
|
|
34
|
+
|
|
35
|
+
# Examples
|
|
36
|
+
examples/*/node_modules/
|
|
37
|
+
examples/*/.yarn/
|
|
38
|
+
examples/*/.pnp.*
|
|
39
|
+
|
|
40
|
+
# Demos
|
|
41
|
+
demos/*/node_modules/
|
|
42
|
+
demos/*/.yarn/
|
|
43
|
+
demos/*/.pnp.*
|
|
44
|
+
|
|
45
|
+
# Regtest (generated by init-regtest.sh and gen-lnd-tls.sh)
|
|
46
|
+
tests/regtest/.env
|
|
47
|
+
tests/regtest/.env.regtest
|
|
48
|
+
tests/regtest/lnd/tls/
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
# Changelog
|
|
2
|
+
|
|
3
|
+
All notable changes to `l402-langchain` will be documented in this file.
|
|
4
|
+
|
|
5
|
+
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
|
|
6
|
+
and this package adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
|
|
7
|
+
|
|
8
|
+
## [0.1.0] — 2026-04-09
|
|
9
|
+
|
|
10
|
+
Initial release. LangChain integration for the L402sdk L402 client SDK.
|
|
11
|
+
|
|
12
|
+
- `L402FetchTool` — LangChain tool for L402-gated API requests with automatic payment
|
|
13
|
+
- `L402BudgetTool` — spending tracker with per-endpoint breakdown
|
|
14
|
+
- `PaymentCallbackHandler` — LangChain callback for payment observability and alerts
|
|
15
|
+
- `create_l402_client()` — factory supporting LND, CLN, and SwissKnife backends
|
|
16
|
+
|
|
17
|
+
[0.1.0]: https://github.com/lightninglabs/L402sdk/releases/tag/l402-langchain-v0.1.0
|
|
@@ -0,0 +1,174 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: l402sdk-langchain
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: LangChain integration for L402sdk — L402 Lightning payments in AI agents
|
|
5
|
+
Project-URL: Homepage, https://github.com/lightninglabs/L402sdk
|
|
6
|
+
Project-URL: Repository, https://github.com/lightninglabs/L402sdk
|
|
7
|
+
Project-URL: Documentation, https://github.com/lightninglabs/L402sdk/tree/main/packages/l402-langchain
|
|
8
|
+
Author-email: Dario Anongba Varela <dario.anongba@gmail.com>
|
|
9
|
+
License-Expression: MIT OR Apache-2.0
|
|
10
|
+
Keywords: ai-agents,bitcoin,l402,langchain,lightning,payments
|
|
11
|
+
Classifier: Development Status :: 3 - Alpha
|
|
12
|
+
Classifier: Intended Audience :: Developers
|
|
13
|
+
Classifier: License :: OSI Approved :: Apache Software License
|
|
14
|
+
Classifier: License :: OSI Approved :: MIT License
|
|
15
|
+
Classifier: Programming Language :: Python :: 3
|
|
16
|
+
Classifier: Programming Language :: Python :: 3.9
|
|
17
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
18
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
19
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
20
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
21
|
+
Classifier: Topic :: Software Development :: Libraries
|
|
22
|
+
Requires-Python: >=3.9
|
|
23
|
+
Requires-Dist: l402sdk>=0.1.0
|
|
24
|
+
Requires-Dist: langchain-core>=0.2.0
|
|
25
|
+
Requires-Dist: pydantic>=2.0
|
|
26
|
+
Provides-Extra: dev
|
|
27
|
+
Requires-Dist: pytest-cov>=4.0; extra == 'dev'
|
|
28
|
+
Requires-Dist: pytest>=7.0; extra == 'dev'
|
|
29
|
+
Description-Content-Type: text/markdown
|
|
30
|
+
|
|
31
|
+
<div align="center">
|
|
32
|
+
<h1>l402-langchain</h1>
|
|
33
|
+
|
|
34
|
+
<p>
|
|
35
|
+
<strong>LangChain tools for L402 Lightning payments</strong>
|
|
36
|
+
</p>
|
|
37
|
+
|
|
38
|
+
<p>
|
|
39
|
+
<a href="https://pypi.org/project/l402-langchain/"><img alt="PyPI" src="https://img.shields.io/pypi/v/l402-langchain.svg"/></a>
|
|
40
|
+
<a href="https://pypi.org/project/l402-langchain/"><img alt="PyPI downloads" src="https://img.shields.io/pypi/dm/l402-langchain.svg"/></a>
|
|
41
|
+
<a href="https://github.com/lightninglabs/L402sdk/blob/main/LICENSE-MIT"><img alt="MIT or Apache-2.0 Licensed" src="https://img.shields.io/badge/license-MIT%2FApache--2.0-blue.svg"/></a>
|
|
42
|
+
</p>
|
|
43
|
+
|
|
44
|
+
</div>
|
|
45
|
+
|
|
46
|
+
Enable AI agents to autonomously pay for [L402](https://docs.lightning.engineering/the-lightning-network/l402)-gated APIs using the Lightning Network.
|
|
47
|
+
|
|
48
|
+
## Install
|
|
49
|
+
|
|
50
|
+
```bash
|
|
51
|
+
pip install l402-langchain
|
|
52
|
+
```
|
|
53
|
+
|
|
54
|
+
## Quick Start
|
|
55
|
+
|
|
56
|
+
```python
|
|
57
|
+
from l402_langchain import create_l402_client, L402FetchTool, L402BudgetTool
|
|
58
|
+
|
|
59
|
+
# Create a client backed by LND REST
|
|
60
|
+
client = create_l402_client(
|
|
61
|
+
backend="lnd",
|
|
62
|
+
url="https://localhost:8080",
|
|
63
|
+
macaroon="hex-encoded-admin-macaroon",
|
|
64
|
+
budget={"per_request_max": 500, "daily_max": 5000},
|
|
65
|
+
)
|
|
66
|
+
|
|
67
|
+
# Create LangChain tools
|
|
68
|
+
fetch_tool = L402FetchTool(client=client)
|
|
69
|
+
budget_tool = L402BudgetTool(client=client)
|
|
70
|
+
|
|
71
|
+
# Use directly
|
|
72
|
+
result = fetch_tool.invoke("https://api.example.com/data")
|
|
73
|
+
print(result)
|
|
74
|
+
# [Paid 100 sats (+0 fee) | status 200]
|
|
75
|
+
# {"ok": true}
|
|
76
|
+
|
|
77
|
+
# Check spending
|
|
78
|
+
print(budget_tool.invoke(""))
|
|
79
|
+
# Total spent: 100 sats across 1 payment(s).
|
|
80
|
+
```
|
|
81
|
+
|
|
82
|
+
## Tools
|
|
83
|
+
|
|
84
|
+
### `L402FetchTool`
|
|
85
|
+
|
|
86
|
+
Makes HTTP requests with automatic L402 payment handling.
|
|
87
|
+
|
|
88
|
+
**Input:** URL string (GET) or JSON `{"url": "...", "body": "..."}` (POST)
|
|
89
|
+
|
|
90
|
+
```python
|
|
91
|
+
# GET
|
|
92
|
+
result = fetch_tool.invoke("https://api.example.com/data")
|
|
93
|
+
|
|
94
|
+
# POST
|
|
95
|
+
result = fetch_tool.invoke('{"url": "https://api.example.com/data", "body": "{\"query\": \"BTC\"}"}')
|
|
96
|
+
```
|
|
97
|
+
|
|
98
|
+
### `L402BudgetTool`
|
|
99
|
+
|
|
100
|
+
Reports spending: total sats, receipt count, per-endpoint breakdown.
|
|
101
|
+
|
|
102
|
+
```python
|
|
103
|
+
result = budget_tool.invoke("")
|
|
104
|
+
# Total spent: 250 sats across 2 payment(s).
|
|
105
|
+
#
|
|
106
|
+
# #1: https://api.example.com/weather — 50 sats (+0 fee, status 200, 5ms)
|
|
107
|
+
# #2: https://api.example.com/market — 200 sats (+0 fee, status 200, 3ms)
|
|
108
|
+
```
|
|
109
|
+
|
|
110
|
+
## Callbacks
|
|
111
|
+
|
|
112
|
+
`PaymentCallbackHandler` hooks into LangChain's callback system for payment observability:
|
|
113
|
+
|
|
114
|
+
```python
|
|
115
|
+
from l402_langchain import PaymentCallbackHandler
|
|
116
|
+
|
|
117
|
+
handler = PaymentCallbackHandler(
|
|
118
|
+
on_payment=lambda event: print(f"Paid {event.amount_sats} sats"),
|
|
119
|
+
max_payment_alert=500,
|
|
120
|
+
on_alert=lambda event: print(f"ALERT: {event.amount_sats} sats!"),
|
|
121
|
+
)
|
|
122
|
+
|
|
123
|
+
# Pass to LangChain agent
|
|
124
|
+
executor.invoke({"input": "..."}, config={"callbacks": [handler]})
|
|
125
|
+
```
|
|
126
|
+
|
|
127
|
+
## Lightning Backends
|
|
128
|
+
|
|
129
|
+
```python
|
|
130
|
+
from l402_langchain import create_l402_client
|
|
131
|
+
|
|
132
|
+
# LND REST
|
|
133
|
+
client = create_l402_client(backend="lnd", url="https://localhost:8080", macaroon="...")
|
|
134
|
+
|
|
135
|
+
# Core Lightning (CLN) REST
|
|
136
|
+
client = create_l402_client(backend="cln", url="https://localhost:3010", rune="...")
|
|
137
|
+
|
|
138
|
+
# SwissKnife
|
|
139
|
+
client = create_l402_client(backend="swissknife", url="https://app.numeraire.tech", api_key="sk-...")
|
|
140
|
+
```
|
|
141
|
+
|
|
142
|
+
## With LangChain Agents
|
|
143
|
+
|
|
144
|
+
```python
|
|
145
|
+
from langchain_openai import ChatOpenAI
|
|
146
|
+
from langchain.agents import create_tool_calling_agent, AgentExecutor
|
|
147
|
+
from langchain_core.prompts import ChatPromptTemplate, MessagesPlaceholder
|
|
148
|
+
from l402_langchain import create_l402_client, L402FetchTool, L402BudgetTool
|
|
149
|
+
|
|
150
|
+
client = create_l402_client(
|
|
151
|
+
backend="lnd",
|
|
152
|
+
url="https://localhost:8080",
|
|
153
|
+
macaroon="deadbeef...",
|
|
154
|
+
budget={"per_request_max": 500},
|
|
155
|
+
)
|
|
156
|
+
|
|
157
|
+
tools = [L402FetchTool(client=client), L402BudgetTool(client=client)]
|
|
158
|
+
llm = ChatOpenAI(model="gpt-4o")
|
|
159
|
+
|
|
160
|
+
prompt = ChatPromptTemplate.from_messages([
|
|
161
|
+
("system", "You can fetch data from L402-gated APIs. "
|
|
162
|
+
"Use l402_fetch for data, l402_check_budget for spending."),
|
|
163
|
+
("human", "{input}"),
|
|
164
|
+
MessagesPlaceholder("agent_scratchpad"),
|
|
165
|
+
])
|
|
166
|
+
|
|
167
|
+
agent = create_tool_calling_agent(llm, tools, prompt)
|
|
168
|
+
executor = AgentExecutor(agent=agent, tools=tools)
|
|
169
|
+
response = executor.invoke({"input": "Get weather data, then report costs."})
|
|
170
|
+
```
|
|
171
|
+
|
|
172
|
+
## License
|
|
173
|
+
|
|
174
|
+
MIT OR Apache-2.0
|
|
@@ -0,0 +1,144 @@
|
|
|
1
|
+
<div align="center">
|
|
2
|
+
<h1>l402-langchain</h1>
|
|
3
|
+
|
|
4
|
+
<p>
|
|
5
|
+
<strong>LangChain tools for L402 Lightning payments</strong>
|
|
6
|
+
</p>
|
|
7
|
+
|
|
8
|
+
<p>
|
|
9
|
+
<a href="https://pypi.org/project/l402-langchain/"><img alt="PyPI" src="https://img.shields.io/pypi/v/l402-langchain.svg"/></a>
|
|
10
|
+
<a href="https://pypi.org/project/l402-langchain/"><img alt="PyPI downloads" src="https://img.shields.io/pypi/dm/l402-langchain.svg"/></a>
|
|
11
|
+
<a href="https://github.com/lightninglabs/L402sdk/blob/main/LICENSE-MIT"><img alt="MIT or Apache-2.0 Licensed" src="https://img.shields.io/badge/license-MIT%2FApache--2.0-blue.svg"/></a>
|
|
12
|
+
</p>
|
|
13
|
+
|
|
14
|
+
</div>
|
|
15
|
+
|
|
16
|
+
Enable AI agents to autonomously pay for [L402](https://docs.lightning.engineering/the-lightning-network/l402)-gated APIs using the Lightning Network.
|
|
17
|
+
|
|
18
|
+
## Install
|
|
19
|
+
|
|
20
|
+
```bash
|
|
21
|
+
pip install l402-langchain
|
|
22
|
+
```
|
|
23
|
+
|
|
24
|
+
## Quick Start
|
|
25
|
+
|
|
26
|
+
```python
|
|
27
|
+
from l402_langchain import create_l402_client, L402FetchTool, L402BudgetTool
|
|
28
|
+
|
|
29
|
+
# Create a client backed by LND REST
|
|
30
|
+
client = create_l402_client(
|
|
31
|
+
backend="lnd",
|
|
32
|
+
url="https://localhost:8080",
|
|
33
|
+
macaroon="hex-encoded-admin-macaroon",
|
|
34
|
+
budget={"per_request_max": 500, "daily_max": 5000},
|
|
35
|
+
)
|
|
36
|
+
|
|
37
|
+
# Create LangChain tools
|
|
38
|
+
fetch_tool = L402FetchTool(client=client)
|
|
39
|
+
budget_tool = L402BudgetTool(client=client)
|
|
40
|
+
|
|
41
|
+
# Use directly
|
|
42
|
+
result = fetch_tool.invoke("https://api.example.com/data")
|
|
43
|
+
print(result)
|
|
44
|
+
# [Paid 100 sats (+0 fee) | status 200]
|
|
45
|
+
# {"ok": true}
|
|
46
|
+
|
|
47
|
+
# Check spending
|
|
48
|
+
print(budget_tool.invoke(""))
|
|
49
|
+
# Total spent: 100 sats across 1 payment(s).
|
|
50
|
+
```
|
|
51
|
+
|
|
52
|
+
## Tools
|
|
53
|
+
|
|
54
|
+
### `L402FetchTool`
|
|
55
|
+
|
|
56
|
+
Makes HTTP requests with automatic L402 payment handling.
|
|
57
|
+
|
|
58
|
+
**Input:** URL string (GET) or JSON `{"url": "...", "body": "..."}` (POST)
|
|
59
|
+
|
|
60
|
+
```python
|
|
61
|
+
# GET
|
|
62
|
+
result = fetch_tool.invoke("https://api.example.com/data")
|
|
63
|
+
|
|
64
|
+
# POST
|
|
65
|
+
result = fetch_tool.invoke('{"url": "https://api.example.com/data", "body": "{\"query\": \"BTC\"}"}')
|
|
66
|
+
```
|
|
67
|
+
|
|
68
|
+
### `L402BudgetTool`
|
|
69
|
+
|
|
70
|
+
Reports spending: total sats, receipt count, per-endpoint breakdown.
|
|
71
|
+
|
|
72
|
+
```python
|
|
73
|
+
result = budget_tool.invoke("")
|
|
74
|
+
# Total spent: 250 sats across 2 payment(s).
|
|
75
|
+
#
|
|
76
|
+
# #1: https://api.example.com/weather — 50 sats (+0 fee, status 200, 5ms)
|
|
77
|
+
# #2: https://api.example.com/market — 200 sats (+0 fee, status 200, 3ms)
|
|
78
|
+
```
|
|
79
|
+
|
|
80
|
+
## Callbacks
|
|
81
|
+
|
|
82
|
+
`PaymentCallbackHandler` hooks into LangChain's callback system for payment observability:
|
|
83
|
+
|
|
84
|
+
```python
|
|
85
|
+
from l402_langchain import PaymentCallbackHandler
|
|
86
|
+
|
|
87
|
+
handler = PaymentCallbackHandler(
|
|
88
|
+
on_payment=lambda event: print(f"Paid {event.amount_sats} sats"),
|
|
89
|
+
max_payment_alert=500,
|
|
90
|
+
on_alert=lambda event: print(f"ALERT: {event.amount_sats} sats!"),
|
|
91
|
+
)
|
|
92
|
+
|
|
93
|
+
# Pass to LangChain agent
|
|
94
|
+
executor.invoke({"input": "..."}, config={"callbacks": [handler]})
|
|
95
|
+
```
|
|
96
|
+
|
|
97
|
+
## Lightning Backends
|
|
98
|
+
|
|
99
|
+
```python
|
|
100
|
+
from l402_langchain import create_l402_client
|
|
101
|
+
|
|
102
|
+
# LND REST
|
|
103
|
+
client = create_l402_client(backend="lnd", url="https://localhost:8080", macaroon="...")
|
|
104
|
+
|
|
105
|
+
# Core Lightning (CLN) REST
|
|
106
|
+
client = create_l402_client(backend="cln", url="https://localhost:3010", rune="...")
|
|
107
|
+
|
|
108
|
+
# SwissKnife
|
|
109
|
+
client = create_l402_client(backend="swissknife", url="https://app.numeraire.tech", api_key="sk-...")
|
|
110
|
+
```
|
|
111
|
+
|
|
112
|
+
## With LangChain Agents
|
|
113
|
+
|
|
114
|
+
```python
|
|
115
|
+
from langchain_openai import ChatOpenAI
|
|
116
|
+
from langchain.agents import create_tool_calling_agent, AgentExecutor
|
|
117
|
+
from langchain_core.prompts import ChatPromptTemplate, MessagesPlaceholder
|
|
118
|
+
from l402_langchain import create_l402_client, L402FetchTool, L402BudgetTool
|
|
119
|
+
|
|
120
|
+
client = create_l402_client(
|
|
121
|
+
backend="lnd",
|
|
122
|
+
url="https://localhost:8080",
|
|
123
|
+
macaroon="deadbeef...",
|
|
124
|
+
budget={"per_request_max": 500},
|
|
125
|
+
)
|
|
126
|
+
|
|
127
|
+
tools = [L402FetchTool(client=client), L402BudgetTool(client=client)]
|
|
128
|
+
llm = ChatOpenAI(model="gpt-4o")
|
|
129
|
+
|
|
130
|
+
prompt = ChatPromptTemplate.from_messages([
|
|
131
|
+
("system", "You can fetch data from L402-gated APIs. "
|
|
132
|
+
"Use l402_fetch for data, l402_check_budget for spending."),
|
|
133
|
+
("human", "{input}"),
|
|
134
|
+
MessagesPlaceholder("agent_scratchpad"),
|
|
135
|
+
])
|
|
136
|
+
|
|
137
|
+
agent = create_tool_calling_agent(llm, tools, prompt)
|
|
138
|
+
executor = AgentExecutor(agent=agent, tools=tools)
|
|
139
|
+
response = executor.invoke({"input": "Get weather data, then report costs."})
|
|
140
|
+
```
|
|
141
|
+
|
|
142
|
+
## License
|
|
143
|
+
|
|
144
|
+
MIT OR Apache-2.0
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["hatchling"]
|
|
3
|
+
build-backend = "hatchling.build"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "l402sdk-langchain"
|
|
7
|
+
version = "0.1.0"
|
|
8
|
+
description = "LangChain integration for L402sdk — L402 Lightning payments in AI agents"
|
|
9
|
+
readme = "README.md"
|
|
10
|
+
license = "MIT OR Apache-2.0"
|
|
11
|
+
requires-python = ">=3.9"
|
|
12
|
+
authors = [
|
|
13
|
+
{ name = "Dario Anongba Varela", email = "dario.anongba@gmail.com" },
|
|
14
|
+
]
|
|
15
|
+
classifiers = [
|
|
16
|
+
"Development Status :: 3 - Alpha",
|
|
17
|
+
"Intended Audience :: Developers",
|
|
18
|
+
"License :: OSI Approved :: MIT License",
|
|
19
|
+
"License :: OSI Approved :: Apache Software License",
|
|
20
|
+
"Programming Language :: Python :: 3",
|
|
21
|
+
"Programming Language :: Python :: 3.9",
|
|
22
|
+
"Programming Language :: Python :: 3.10",
|
|
23
|
+
"Programming Language :: Python :: 3.11",
|
|
24
|
+
"Programming Language :: Python :: 3.12",
|
|
25
|
+
"Programming Language :: Python :: 3.13",
|
|
26
|
+
"Topic :: Software Development :: Libraries",
|
|
27
|
+
]
|
|
28
|
+
keywords = ["l402", "lightning", "bitcoin", "langchain", "ai-agents", "payments"]
|
|
29
|
+
dependencies = [
|
|
30
|
+
"L402sdk>=0.1.0",
|
|
31
|
+
"langchain-core>=0.2.0",
|
|
32
|
+
"pydantic>=2.0",
|
|
33
|
+
]
|
|
34
|
+
|
|
35
|
+
[project.optional-dependencies]
|
|
36
|
+
dev = [
|
|
37
|
+
"pytest>=7.0",
|
|
38
|
+
"pytest-cov>=4.0",
|
|
39
|
+
]
|
|
40
|
+
|
|
41
|
+
[project.urls]
|
|
42
|
+
Homepage = "https://github.com/lightninglabs/L402sdk"
|
|
43
|
+
Repository = "https://github.com/lightninglabs/L402sdk"
|
|
44
|
+
Documentation = "https://github.com/lightninglabs/L402sdk/tree/main/packages/l402-langchain"
|
|
45
|
+
|
|
46
|
+
[tool.hatch.build.targets.wheel]
|
|
47
|
+
packages = ["src/l402_langchain"]
|
|
48
|
+
|
|
49
|
+
[tool.pytest.ini_options]
|
|
50
|
+
testpaths = ["tests"]
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
"""l402-langchain: LangChain integration for L402 Lightning payments.
|
|
2
|
+
|
|
3
|
+
Provides LangChain tools that enable AI agents to autonomously pay for
|
|
4
|
+
L402-gated APIs using Lightning Network payments via L402sdk.
|
|
5
|
+
|
|
6
|
+
Quick start::
|
|
7
|
+
|
|
8
|
+
from l402_langchain import create_l402_client, L402FetchTool
|
|
9
|
+
|
|
10
|
+
client = create_l402_client(
|
|
11
|
+
backend="lnd",
|
|
12
|
+
url="https://localhost:8080",
|
|
13
|
+
macaroon="deadbeef...",
|
|
14
|
+
)
|
|
15
|
+
fetch = L402FetchTool(client=client)
|
|
16
|
+
result = fetch.invoke("https://api.example.com/data")
|
|
17
|
+
|
|
18
|
+
Classes:
|
|
19
|
+
L402FetchTool: LangChain tool for L402-aware HTTP requests.
|
|
20
|
+
L402BudgetTool: LangChain tool for spending monitoring.
|
|
21
|
+
PaymentCallbackHandler: LangChain callback for payment events.
|
|
22
|
+
|
|
23
|
+
Functions:
|
|
24
|
+
create_l402_client: Factory for creating configured L402 clients.
|
|
25
|
+
"""
|
|
26
|
+
|
|
27
|
+
from l402_langchain.callbacks import PaymentCallbackHandler
|
|
28
|
+
from l402_langchain.config import create_l402_client
|
|
29
|
+
from l402_langchain.tools import L402BudgetTool, L402FetchTool
|
|
30
|
+
|
|
31
|
+
__all__ = [
|
|
32
|
+
"L402FetchTool",
|
|
33
|
+
"L402BudgetTool",
|
|
34
|
+
"PaymentCallbackHandler",
|
|
35
|
+
"create_l402_client",
|
|
36
|
+
]
|
|
37
|
+
|
|
38
|
+
__version__ = "0.1.0"
|
|
@@ -0,0 +1,161 @@
|
|
|
1
|
+
"""LangChain callback handler for L402 payment events.
|
|
2
|
+
|
|
3
|
+
Provides ``PaymentCallbackHandler`` that hooks into LangChain's callback
|
|
4
|
+
system to observe and react to L402 payments made by tools. Useful for
|
|
5
|
+
logging, alerting, cost monitoring, and integration with external systems.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import re
|
|
11
|
+
from typing import Any, Callable, Optional
|
|
12
|
+
|
|
13
|
+
from langchain_core.callbacks import BaseCallbackHandler
|
|
14
|
+
|
|
15
|
+
# Pattern to extract payment info from tool output
|
|
16
|
+
_PAYMENT_PATTERN = re.compile(
|
|
17
|
+
r"\[Paid (\d+) sats \(\+(\d+) fee\) \| status (\d+)\]"
|
|
18
|
+
)
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
class PaymentEvent:
|
|
22
|
+
"""Represents an L402 payment event extracted from tool output.
|
|
23
|
+
|
|
24
|
+
Attributes:
|
|
25
|
+
amount_sats: Amount paid in satoshis (excluding fees).
|
|
26
|
+
fee_sats: Routing fee in satoshis.
|
|
27
|
+
status: HTTP response status code after payment.
|
|
28
|
+
tool_name: Name of the LangChain tool that made the payment.
|
|
29
|
+
tool_input: Input that was passed to the tool.
|
|
30
|
+
"""
|
|
31
|
+
|
|
32
|
+
__slots__ = ("amount_sats", "fee_sats", "status", "tool_name", "tool_input")
|
|
33
|
+
|
|
34
|
+
def __init__(
|
|
35
|
+
self,
|
|
36
|
+
amount_sats: int,
|
|
37
|
+
fee_sats: int,
|
|
38
|
+
status: int,
|
|
39
|
+
tool_name: str,
|
|
40
|
+
tool_input: str,
|
|
41
|
+
) -> None:
|
|
42
|
+
self.amount_sats = amount_sats
|
|
43
|
+
self.fee_sats = fee_sats
|
|
44
|
+
self.status = status
|
|
45
|
+
self.tool_name = tool_name
|
|
46
|
+
self.tool_input = tool_input
|
|
47
|
+
|
|
48
|
+
@property
|
|
49
|
+
def total_sats(self) -> int:
|
|
50
|
+
"""Total cost including routing fees."""
|
|
51
|
+
return self.amount_sats + self.fee_sats
|
|
52
|
+
|
|
53
|
+
def __repr__(self) -> str:
|
|
54
|
+
return (
|
|
55
|
+
f"PaymentEvent(amount_sats={self.amount_sats}, "
|
|
56
|
+
f"fee_sats={self.fee_sats}, status={self.status}, "
|
|
57
|
+
f"tool={self.tool_name!r})"
|
|
58
|
+
)
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
class PaymentCallbackHandler(BaseCallbackHandler):
|
|
62
|
+
"""LangChain callback handler that fires on L402 payment events.
|
|
63
|
+
|
|
64
|
+
Hooks into ``on_tool_end`` to parse payment metadata from tool output.
|
|
65
|
+
When a payment is detected, calls the configured callback functions.
|
|
66
|
+
|
|
67
|
+
Example::
|
|
68
|
+
|
|
69
|
+
from l402_langchain import PaymentCallbackHandler
|
|
70
|
+
|
|
71
|
+
payments = []
|
|
72
|
+
handler = PaymentCallbackHandler(
|
|
73
|
+
on_payment=lambda event: payments.append(event),
|
|
74
|
+
max_payment_alert=500,
|
|
75
|
+
on_alert=lambda event: print(f"ALERT: {event.amount_sats} sats!"),
|
|
76
|
+
)
|
|
77
|
+
|
|
78
|
+
# Pass to LangChain agent
|
|
79
|
+
executor.invoke({"input": "..."}, config={"callbacks": [handler]})
|
|
80
|
+
"""
|
|
81
|
+
|
|
82
|
+
def __init__(
|
|
83
|
+
self,
|
|
84
|
+
on_payment: Optional[Callable[[PaymentEvent], None]] = None,
|
|
85
|
+
on_alert: Optional[Callable[[PaymentEvent], None]] = None,
|
|
86
|
+
max_payment_alert: Optional[int] = None,
|
|
87
|
+
) -> None:
|
|
88
|
+
"""Initialize the callback handler.
|
|
89
|
+
|
|
90
|
+
Args:
|
|
91
|
+
on_payment: Called for every detected payment event.
|
|
92
|
+
on_alert: Called when a payment exceeds ``max_payment_alert``.
|
|
93
|
+
max_payment_alert: Satoshi threshold for triggering alerts.
|
|
94
|
+
If ``None``, alerts are disabled.
|
|
95
|
+
"""
|
|
96
|
+
super().__init__()
|
|
97
|
+
self._on_payment = on_payment
|
|
98
|
+
self._on_alert = on_alert
|
|
99
|
+
self._max_payment_alert = max_payment_alert
|
|
100
|
+
self._total_spent: int = 0
|
|
101
|
+
self._payment_count: int = 0
|
|
102
|
+
|
|
103
|
+
@property
|
|
104
|
+
def total_spent(self) -> int:
|
|
105
|
+
"""Total satoshis observed across all payments."""
|
|
106
|
+
return self._total_spent
|
|
107
|
+
|
|
108
|
+
@property
|
|
109
|
+
def payment_count(self) -> int:
|
|
110
|
+
"""Number of payments observed."""
|
|
111
|
+
return self._payment_count
|
|
112
|
+
|
|
113
|
+
def on_tool_end(
|
|
114
|
+
self,
|
|
115
|
+
output: Any,
|
|
116
|
+
*,
|
|
117
|
+
run_id: Any = None,
|
|
118
|
+
parent_run_id: Any = None,
|
|
119
|
+
tags: Optional[list[str]] = None,
|
|
120
|
+
**kwargs: Any,
|
|
121
|
+
) -> None:
|
|
122
|
+
"""Process tool output and extract payment events.
|
|
123
|
+
|
|
124
|
+
Called by LangChain after a tool finishes execution. Parses the
|
|
125
|
+
output string for payment metadata and fires callbacks.
|
|
126
|
+
"""
|
|
127
|
+
output_str = str(output)
|
|
128
|
+
match = _PAYMENT_PATTERN.search(output_str)
|
|
129
|
+
if not match:
|
|
130
|
+
return
|
|
131
|
+
|
|
132
|
+
amount_sats = int(match.group(1))
|
|
133
|
+
fee_sats = int(match.group(2))
|
|
134
|
+
status = int(match.group(3))
|
|
135
|
+
|
|
136
|
+
# Extract tool metadata from kwargs if available
|
|
137
|
+
tool_name = kwargs.get("name", "unknown")
|
|
138
|
+
tool_input = kwargs.get("tool_input", "")
|
|
139
|
+
if isinstance(tool_input, dict):
|
|
140
|
+
tool_input = str(tool_input)
|
|
141
|
+
|
|
142
|
+
event = PaymentEvent(
|
|
143
|
+
amount_sats=amount_sats,
|
|
144
|
+
fee_sats=fee_sats,
|
|
145
|
+
status=status,
|
|
146
|
+
tool_name=tool_name,
|
|
147
|
+
tool_input=str(tool_input),
|
|
148
|
+
)
|
|
149
|
+
|
|
150
|
+
self._total_spent += event.total_sats
|
|
151
|
+
self._payment_count += 1
|
|
152
|
+
|
|
153
|
+
if self._on_payment is not None:
|
|
154
|
+
self._on_payment(event)
|
|
155
|
+
|
|
156
|
+
if (
|
|
157
|
+
self._on_alert is not None
|
|
158
|
+
and self._max_payment_alert is not None
|
|
159
|
+
and amount_sats > self._max_payment_alert
|
|
160
|
+
):
|
|
161
|
+
self._on_alert(event)
|
|
@@ -0,0 +1,165 @@
|
|
|
1
|
+
"""Configuration helpers for creating L402sdk clients.
|
|
2
|
+
|
|
3
|
+
Provides ``create_l402_client()`` as a convenient factory function for
|
|
4
|
+
LangChain users who want a quick-start setup without learning the full
|
|
5
|
+
L402sdk API.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
from typing import Any, Optional, Union
|
|
11
|
+
|
|
12
|
+
from l402 import Budget, L402Client
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
def create_l402_client(
|
|
16
|
+
*,
|
|
17
|
+
backend: str,
|
|
18
|
+
url: str,
|
|
19
|
+
macaroon: Optional[str] = None,
|
|
20
|
+
tls_cert_path: Optional[str] = None,
|
|
21
|
+
macaroon_path: Optional[str] = None,
|
|
22
|
+
rune: Optional[str] = None,
|
|
23
|
+
ca_cert_path: Optional[str] = None,
|
|
24
|
+
client_cert_path: Optional[str] = None,
|
|
25
|
+
client_key_path: Optional[str] = None,
|
|
26
|
+
api_key: Optional[str] = None,
|
|
27
|
+
budget: Optional[Union[Budget, dict[str, Any]]] = None,
|
|
28
|
+
max_fee_sats: int = 100,
|
|
29
|
+
) -> L402Client:
|
|
30
|
+
"""Create a configured L402 client for use with LangChain tools.
|
|
31
|
+
|
|
32
|
+
Factory function that simplifies client creation. Supports LND
|
|
33
|
+
(gRPC + REST), CLN (gRPC + REST), and SwissKnife backends.
|
|
34
|
+
|
|
35
|
+
Args:
|
|
36
|
+
backend: Lightning backend type. One of ``"lnd"``, ``"lnd-grpc"``,
|
|
37
|
+
``"cln"``, ``"cln-grpc"``, or ``"swissknife"``.
|
|
38
|
+
url: Backend API URL.
|
|
39
|
+
macaroon: Hex-encoded admin macaroon. Required for ``"lnd"``
|
|
40
|
+
(REST) backend.
|
|
41
|
+
tls_cert_path: Path to LND's ``tls.cert``. Required for
|
|
42
|
+
``"lnd-grpc"`` backend.
|
|
43
|
+
macaroon_path: Path to admin macaroon file. Required for
|
|
44
|
+
``"lnd-grpc"`` backend.
|
|
45
|
+
rune: Rune token string. Required for ``"cln"`` (REST) backend.
|
|
46
|
+
ca_cert_path: Path to CA cert. Required for ``"cln-grpc"``.
|
|
47
|
+
client_cert_path: Path to client cert. Required for ``"cln-grpc"``.
|
|
48
|
+
client_key_path: Path to client key. Required for ``"cln-grpc"``.
|
|
49
|
+
api_key: API key. Required for ``"swissknife"`` backend.
|
|
50
|
+
budget: Spending limits. Can be a ``Budget`` instance or a dict
|
|
51
|
+
with keys ``per_request_max``, ``hourly_max``, ``daily_max``,
|
|
52
|
+
``total_max``.
|
|
53
|
+
max_fee_sats: Maximum routing fee in satoshis per payment.
|
|
54
|
+
|
|
55
|
+
Returns:
|
|
56
|
+
A configured ``L402Client`` instance.
|
|
57
|
+
|
|
58
|
+
Raises:
|
|
59
|
+
ValueError: If the backend is not supported or required parameters
|
|
60
|
+
are missing.
|
|
61
|
+
|
|
62
|
+
Example::
|
|
63
|
+
|
|
64
|
+
from l402_langchain import create_l402_client
|
|
65
|
+
|
|
66
|
+
client = create_l402_client(
|
|
67
|
+
backend="lnd",
|
|
68
|
+
url="https://localhost:8080",
|
|
69
|
+
macaroon="deadbeef...",
|
|
70
|
+
budget={"per_request_max": 200, "daily_max": 5000},
|
|
71
|
+
)
|
|
72
|
+
"""
|
|
73
|
+
resolved_budget = _resolve_budget(budget)
|
|
74
|
+
|
|
75
|
+
if backend == "lnd":
|
|
76
|
+
if not macaroon:
|
|
77
|
+
raise ValueError(
|
|
78
|
+
"macaroon is required for LND backend. "
|
|
79
|
+
"Provide a hex-encoded admin macaroon."
|
|
80
|
+
)
|
|
81
|
+
return L402Client.with_lnd_rest(
|
|
82
|
+
url,
|
|
83
|
+
macaroon,
|
|
84
|
+
budget=resolved_budget,
|
|
85
|
+
max_fee_sats=max_fee_sats,
|
|
86
|
+
)
|
|
87
|
+
|
|
88
|
+
if backend == "lnd-grpc":
|
|
89
|
+
if not tls_cert_path or not macaroon_path:
|
|
90
|
+
raise ValueError(
|
|
91
|
+
"tls_cert_path and macaroon_path are required for LND gRPC backend."
|
|
92
|
+
)
|
|
93
|
+
return L402Client.with_lnd_grpc(
|
|
94
|
+
url,
|
|
95
|
+
tls_cert_path,
|
|
96
|
+
macaroon_path,
|
|
97
|
+
budget=resolved_budget,
|
|
98
|
+
max_fee_sats=max_fee_sats,
|
|
99
|
+
)
|
|
100
|
+
|
|
101
|
+
if backend == "cln":
|
|
102
|
+
if not rune:
|
|
103
|
+
raise ValueError(
|
|
104
|
+
"rune is required for CLN backend. "
|
|
105
|
+
"Provide a CLN rune token string."
|
|
106
|
+
)
|
|
107
|
+
return L402Client.with_cln_rest(
|
|
108
|
+
url,
|
|
109
|
+
rune,
|
|
110
|
+
budget=resolved_budget,
|
|
111
|
+
max_fee_sats=max_fee_sats,
|
|
112
|
+
)
|
|
113
|
+
|
|
114
|
+
if backend == "cln-grpc":
|
|
115
|
+
if not ca_cert_path or not client_cert_path or not client_key_path:
|
|
116
|
+
raise ValueError(
|
|
117
|
+
"ca_cert_path, client_cert_path, and client_key_path are required "
|
|
118
|
+
"for CLN gRPC backend."
|
|
119
|
+
)
|
|
120
|
+
return L402Client.with_cln_grpc(
|
|
121
|
+
url,
|
|
122
|
+
ca_cert_path,
|
|
123
|
+
client_cert_path,
|
|
124
|
+
client_key_path,
|
|
125
|
+
budget=resolved_budget,
|
|
126
|
+
max_fee_sats=max_fee_sats,
|
|
127
|
+
)
|
|
128
|
+
|
|
129
|
+
if backend == "swissknife":
|
|
130
|
+
if not api_key:
|
|
131
|
+
raise ValueError(
|
|
132
|
+
"api_key is required for SwissKnife backend. "
|
|
133
|
+
"Provide a SwissKnife API key."
|
|
134
|
+
)
|
|
135
|
+
return L402Client.with_swissknife(
|
|
136
|
+
url,
|
|
137
|
+
api_key,
|
|
138
|
+
budget=resolved_budget,
|
|
139
|
+
max_fee_sats=max_fee_sats,
|
|
140
|
+
)
|
|
141
|
+
|
|
142
|
+
raise ValueError(
|
|
143
|
+
f"Unsupported backend: {backend!r}. "
|
|
144
|
+
f"Supported: 'lnd', 'lnd-grpc', 'cln', 'cln-grpc', 'swissknife'."
|
|
145
|
+
)
|
|
146
|
+
|
|
147
|
+
|
|
148
|
+
def _resolve_budget(
|
|
149
|
+
budget: Optional[Union[Budget, dict[str, Any]]],
|
|
150
|
+
) -> Optional[Budget]:
|
|
151
|
+
"""Convert a budget dict to a Budget instance, or pass through."""
|
|
152
|
+
if budget is None:
|
|
153
|
+
return None
|
|
154
|
+
if isinstance(budget, Budget):
|
|
155
|
+
return budget
|
|
156
|
+
if isinstance(budget, dict):
|
|
157
|
+
return Budget(
|
|
158
|
+
per_request_max=budget.get("per_request_max"),
|
|
159
|
+
hourly_max=budget.get("hourly_max"),
|
|
160
|
+
daily_max=budget.get("daily_max"),
|
|
161
|
+
total_max=budget.get("total_max"),
|
|
162
|
+
)
|
|
163
|
+
raise TypeError(
|
|
164
|
+
f"budget must be a Budget instance or dict, got {type(budget).__name__}"
|
|
165
|
+
)
|
|
@@ -0,0 +1,178 @@
|
|
|
1
|
+
"""LangChain tools for L402-gated API access via L402sdk.
|
|
2
|
+
|
|
3
|
+
Provides ``L402FetchTool`` for making HTTP requests that automatically
|
|
4
|
+
handle L402 payment challenges, and ``L402BudgetTool`` for monitoring
|
|
5
|
+
spending across all L402 interactions.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import json
|
|
11
|
+
from typing import Any, ClassVar, Optional
|
|
12
|
+
|
|
13
|
+
from langchain_core.tools import BaseTool
|
|
14
|
+
from pydantic import ConfigDict, Field
|
|
15
|
+
|
|
16
|
+
from l402 import L402Client, L402Response
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
class L402FetchTool(BaseTool):
|
|
20
|
+
"""LangChain tool for fetching data from L402-gated APIs.
|
|
21
|
+
|
|
22
|
+
Wraps a ``L402sdk.L402Client`` to handle the full L402 payment flow
|
|
23
|
+
transparently: HTTP 402 -> parse challenge -> pay Lightning invoice ->
|
|
24
|
+
retry with token -> return data.
|
|
25
|
+
|
|
26
|
+
Budget limits configured on the client are enforced automatically.
|
|
27
|
+
Token caching is handled by L402sdk so repeated requests to the same
|
|
28
|
+
endpoint reuse cached tokens without additional payments.
|
|
29
|
+
|
|
30
|
+
Example::
|
|
31
|
+
|
|
32
|
+
from l402_langchain import create_l402_client, L402FetchTool
|
|
33
|
+
|
|
34
|
+
client = create_l402_client(
|
|
35
|
+
backend="lnd",
|
|
36
|
+
url="https://localhost:8080",
|
|
37
|
+
macaroon="deadbeef...",
|
|
38
|
+
)
|
|
39
|
+
tool = L402FetchTool(client=client)
|
|
40
|
+
result = tool.invoke("https://api.example.com/data")
|
|
41
|
+
"""
|
|
42
|
+
|
|
43
|
+
name: ClassVar[str] = "l402_fetch"
|
|
44
|
+
description: ClassVar[str] = (
|
|
45
|
+
"Fetch data from an API that requires Lightning payment (L402). "
|
|
46
|
+
"Input should be a full URL, or a JSON object with 'url' and "
|
|
47
|
+
"optional 'body' for POST requests. The tool automatically handles "
|
|
48
|
+
"payment if the API responds with HTTP 402. Returns the response "
|
|
49
|
+
"body with payment metadata."
|
|
50
|
+
)
|
|
51
|
+
|
|
52
|
+
model_config = ConfigDict(arbitrary_types_allowed=True)
|
|
53
|
+
|
|
54
|
+
client: L402Client = Field(exclude=True)
|
|
55
|
+
|
|
56
|
+
def _run(self, input_str: str) -> str:
|
|
57
|
+
"""Execute an L402-aware HTTP request.
|
|
58
|
+
|
|
59
|
+
Args:
|
|
60
|
+
input_str: Either a plain URL for GET requests, or a JSON
|
|
61
|
+
string ``{"url": "...", "body": "..."}`` for POST requests.
|
|
62
|
+
|
|
63
|
+
Returns:
|
|
64
|
+
Response body prefixed with payment metadata. On error,
|
|
65
|
+
returns a descriptive error string (not an exception) so the
|
|
66
|
+
LLM agent can reason about the failure.
|
|
67
|
+
"""
|
|
68
|
+
url, body = _parse_input(input_str)
|
|
69
|
+
|
|
70
|
+
try:
|
|
71
|
+
if body is not None:
|
|
72
|
+
response: L402Response = self.client.post(url, body)
|
|
73
|
+
else:
|
|
74
|
+
response = self.client.get(url)
|
|
75
|
+
except ValueError as exc:
|
|
76
|
+
return f"Payment error: {exc}"
|
|
77
|
+
except RuntimeError as exc:
|
|
78
|
+
return f"Request error: {exc}"
|
|
79
|
+
|
|
80
|
+
return _format_response(response)
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
class L402BudgetTool(BaseTool):
|
|
84
|
+
"""LangChain tool for monitoring L402 spending.
|
|
85
|
+
|
|
86
|
+
Reports total satoshis spent, number of payments, and a per-endpoint
|
|
87
|
+
breakdown. Useful for cost-aware agents that need to track or report
|
|
88
|
+
their API spending.
|
|
89
|
+
|
|
90
|
+
Example::
|
|
91
|
+
|
|
92
|
+
from l402_langchain import create_l402_client, L402BudgetTool
|
|
93
|
+
|
|
94
|
+
client = create_l402_client(
|
|
95
|
+
backend="lnd",
|
|
96
|
+
url="https://localhost:8080",
|
|
97
|
+
macaroon="deadbeef...",
|
|
98
|
+
)
|
|
99
|
+
tool = L402BudgetTool(client=client)
|
|
100
|
+
result = tool.invoke("") # "No payments made yet. ..."
|
|
101
|
+
"""
|
|
102
|
+
|
|
103
|
+
name: ClassVar[str] = "l402_check_budget"
|
|
104
|
+
description: ClassVar[str] = (
|
|
105
|
+
"Check total Lightning sats spent so far across all L402 API "
|
|
106
|
+
"calls. Takes no input. Returns total sats spent, receipt count, "
|
|
107
|
+
"and a breakdown per endpoint."
|
|
108
|
+
)
|
|
109
|
+
|
|
110
|
+
model_config = ConfigDict(arbitrary_types_allowed=True)
|
|
111
|
+
|
|
112
|
+
client: L402Client = Field(exclude=True)
|
|
113
|
+
|
|
114
|
+
def _run(self, _input: str = "") -> str:
|
|
115
|
+
"""Return a spending summary.
|
|
116
|
+
|
|
117
|
+
Returns:
|
|
118
|
+
Human-readable spending report with total sats, receipt
|
|
119
|
+
count, and per-endpoint breakdown.
|
|
120
|
+
"""
|
|
121
|
+
total = self.client.total_spent()
|
|
122
|
+
receipts = self.client.receipts()
|
|
123
|
+
|
|
124
|
+
if not receipts:
|
|
125
|
+
return "No payments made yet. Total spent: 0 sats."
|
|
126
|
+
|
|
127
|
+
lines = [
|
|
128
|
+
f"Total spent: {total} sats across {len(receipts)} payment(s).",
|
|
129
|
+
"",
|
|
130
|
+
]
|
|
131
|
+
for i, receipt in enumerate(receipts, 1):
|
|
132
|
+
lines.append(
|
|
133
|
+
f" #{i}: {receipt.endpoint} — "
|
|
134
|
+
f"{receipt.amount_sats} sats "
|
|
135
|
+
f"(+{receipt.fee_sats} fee, "
|
|
136
|
+
f"status {receipt.response_status}, "
|
|
137
|
+
f"{receipt.latency_ms}ms)"
|
|
138
|
+
)
|
|
139
|
+
|
|
140
|
+
return "\n".join(lines)
|
|
141
|
+
|
|
142
|
+
|
|
143
|
+
def _parse_input(input_str: str) -> tuple[str, Optional[str]]:
|
|
144
|
+
"""Parse tool input into (url, optional_body).
|
|
145
|
+
|
|
146
|
+
Accepts either a plain URL string or a JSON object with 'url' and
|
|
147
|
+
optional 'body' keys.
|
|
148
|
+
"""
|
|
149
|
+
stripped = input_str.strip()
|
|
150
|
+
|
|
151
|
+
# Try JSON parse for POST requests
|
|
152
|
+
if stripped.startswith("{"):
|
|
153
|
+
try:
|
|
154
|
+
data = json.loads(stripped)
|
|
155
|
+
url = data.get("url", "")
|
|
156
|
+
body = data.get("body")
|
|
157
|
+
if isinstance(body, dict):
|
|
158
|
+
body = json.dumps(body)
|
|
159
|
+
return url, body
|
|
160
|
+
except (json.JSONDecodeError, AttributeError):
|
|
161
|
+
pass
|
|
162
|
+
|
|
163
|
+
# Plain URL for GET requests
|
|
164
|
+
return stripped, None
|
|
165
|
+
|
|
166
|
+
|
|
167
|
+
def _format_response(response: L402Response) -> str:
|
|
168
|
+
"""Format an L402Response into a human-readable string with metadata."""
|
|
169
|
+
if response.paid and response.receipt is not None:
|
|
170
|
+
receipt = response.receipt
|
|
171
|
+
header = (
|
|
172
|
+
f"[Paid {receipt.amount_sats} sats "
|
|
173
|
+
f"(+{receipt.fee_sats} fee) | "
|
|
174
|
+
f"status {response.status}]\n"
|
|
175
|
+
)
|
|
176
|
+
return header + response.text()
|
|
177
|
+
|
|
178
|
+
return f"[No payment | status {response.status}]\n{response.text()}"
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
"""Shared test fixtures for l402-langchain tests."""
|
|
2
|
+
|
|
3
|
+
import pytest
|
|
4
|
+
|
|
5
|
+
from l402 import Budget, L402Client
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
@pytest.fixture()
|
|
9
|
+
def client_setup():
|
|
10
|
+
"""Create a client with dummy LND credentials for constructor tests.
|
|
11
|
+
|
|
12
|
+
This client cannot make real requests but is valid for testing tool
|
|
13
|
+
construction, metadata, and budget reporting.
|
|
14
|
+
"""
|
|
15
|
+
client = L402Client.with_lnd_rest(
|
|
16
|
+
"https://localhost:8080",
|
|
17
|
+
"deadbeef0123456789",
|
|
18
|
+
)
|
|
19
|
+
return {"client": client}
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
@pytest.fixture()
|
|
23
|
+
def budget_client_setup():
|
|
24
|
+
"""Create a client with budget limits and dummy LND credentials.
|
|
25
|
+
|
|
26
|
+
Budget: 500 sats per request, 2000 sats daily.
|
|
27
|
+
"""
|
|
28
|
+
budget = Budget(per_request_max=500, daily_max=2000)
|
|
29
|
+
client = L402Client.with_lnd_rest(
|
|
30
|
+
"https://localhost:8080",
|
|
31
|
+
"deadbeef0123456789",
|
|
32
|
+
budget=budget,
|
|
33
|
+
)
|
|
34
|
+
return {"client": client}
|
|
@@ -0,0 +1,140 @@
|
|
|
1
|
+
"""Tests for PaymentCallbackHandler."""
|
|
2
|
+
|
|
3
|
+
from l402_langchain.callbacks import PaymentCallbackHandler, PaymentEvent
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
class TestPaymentEvent:
|
|
7
|
+
"""Tests for the PaymentEvent data class."""
|
|
8
|
+
|
|
9
|
+
def test_total_sats(self):
|
|
10
|
+
"""Total sats includes amount plus fee."""
|
|
11
|
+
event = PaymentEvent(
|
|
12
|
+
amount_sats=100,
|
|
13
|
+
fee_sats=5,
|
|
14
|
+
status=200,
|
|
15
|
+
tool_name="l402_fetch",
|
|
16
|
+
tool_input="https://example.com",
|
|
17
|
+
)
|
|
18
|
+
assert event.total_sats == 105
|
|
19
|
+
|
|
20
|
+
def test_repr(self):
|
|
21
|
+
"""Repr includes key fields."""
|
|
22
|
+
event = PaymentEvent(
|
|
23
|
+
amount_sats=100,
|
|
24
|
+
fee_sats=5,
|
|
25
|
+
status=200,
|
|
26
|
+
tool_name="l402_fetch",
|
|
27
|
+
tool_input="https://example.com",
|
|
28
|
+
)
|
|
29
|
+
repr_str = repr(event)
|
|
30
|
+
assert "amount_sats=100" in repr_str
|
|
31
|
+
assert "fee_sats=5" in repr_str
|
|
32
|
+
assert "l402_fetch" in repr_str
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
class TestPaymentCallbackHandler:
|
|
36
|
+
"""Tests for the PaymentCallbackHandler."""
|
|
37
|
+
|
|
38
|
+
def test_detects_payment(self):
|
|
39
|
+
"""Handler fires on_payment when tool output contains payment info."""
|
|
40
|
+
events = []
|
|
41
|
+
handler = PaymentCallbackHandler(
|
|
42
|
+
on_payment=lambda e: events.append(e),
|
|
43
|
+
)
|
|
44
|
+
|
|
45
|
+
handler.on_tool_end(
|
|
46
|
+
"[Paid 100 sats (+5 fee) | status 200]\n{\"ok\": true}",
|
|
47
|
+
name="l402_fetch",
|
|
48
|
+
)
|
|
49
|
+
|
|
50
|
+
assert len(events) == 1
|
|
51
|
+
assert events[0].amount_sats == 100
|
|
52
|
+
assert events[0].fee_sats == 5
|
|
53
|
+
assert events[0].status == 200
|
|
54
|
+
|
|
55
|
+
def test_ignores_non_payment(self):
|
|
56
|
+
"""Handler does not fire on tool output without payment info."""
|
|
57
|
+
events = []
|
|
58
|
+
handler = PaymentCallbackHandler(
|
|
59
|
+
on_payment=lambda e: events.append(e),
|
|
60
|
+
)
|
|
61
|
+
|
|
62
|
+
handler.on_tool_end(
|
|
63
|
+
"[No payment | status 200]\n{\"ok\": true}",
|
|
64
|
+
name="l402_fetch",
|
|
65
|
+
)
|
|
66
|
+
|
|
67
|
+
assert len(events) == 0
|
|
68
|
+
|
|
69
|
+
def test_tracks_total_spent(self):
|
|
70
|
+
"""Handler accumulates total spending."""
|
|
71
|
+
handler = PaymentCallbackHandler()
|
|
72
|
+
|
|
73
|
+
handler.on_tool_end(
|
|
74
|
+
"[Paid 100 sats (+5 fee) | status 200]\ndata",
|
|
75
|
+
name="l402_fetch",
|
|
76
|
+
)
|
|
77
|
+
handler.on_tool_end(
|
|
78
|
+
"[Paid 200 sats (+10 fee) | status 200]\ndata",
|
|
79
|
+
name="l402_fetch",
|
|
80
|
+
)
|
|
81
|
+
|
|
82
|
+
assert handler.total_spent == 315 # (100+5) + (200+10)
|
|
83
|
+
assert handler.payment_count == 2
|
|
84
|
+
|
|
85
|
+
def test_alert_triggered(self):
|
|
86
|
+
"""Alert fires when payment exceeds threshold."""
|
|
87
|
+
alerts = []
|
|
88
|
+
handler = PaymentCallbackHandler(
|
|
89
|
+
max_payment_alert=150,
|
|
90
|
+
on_alert=lambda e: alerts.append(e),
|
|
91
|
+
)
|
|
92
|
+
|
|
93
|
+
# Below threshold: no alert
|
|
94
|
+
handler.on_tool_end(
|
|
95
|
+
"[Paid 100 sats (+5 fee) | status 200]\ndata",
|
|
96
|
+
name="l402_fetch",
|
|
97
|
+
)
|
|
98
|
+
assert len(alerts) == 0
|
|
99
|
+
|
|
100
|
+
# Above threshold: alert
|
|
101
|
+
handler.on_tool_end(
|
|
102
|
+
"[Paid 200 sats (+10 fee) | status 200]\ndata",
|
|
103
|
+
name="l402_fetch",
|
|
104
|
+
)
|
|
105
|
+
assert len(alerts) == 1
|
|
106
|
+
assert alerts[0].amount_sats == 200
|
|
107
|
+
|
|
108
|
+
def test_no_alert_when_disabled(self):
|
|
109
|
+
"""No alert fires when max_payment_alert is not set."""
|
|
110
|
+
alerts = []
|
|
111
|
+
handler = PaymentCallbackHandler(
|
|
112
|
+
on_alert=lambda e: alerts.append(e),
|
|
113
|
+
)
|
|
114
|
+
|
|
115
|
+
handler.on_tool_end(
|
|
116
|
+
"[Paid 99999 sats (+100 fee) | status 200]\ndata",
|
|
117
|
+
name="l402_fetch",
|
|
118
|
+
)
|
|
119
|
+
|
|
120
|
+
assert len(alerts) == 0
|
|
121
|
+
|
|
122
|
+
def test_initial_state(self):
|
|
123
|
+
"""Handler starts with zero spent and zero payments."""
|
|
124
|
+
handler = PaymentCallbackHandler()
|
|
125
|
+
assert handler.total_spent == 0
|
|
126
|
+
assert handler.payment_count == 0
|
|
127
|
+
|
|
128
|
+
def test_ignores_budget_errors(self):
|
|
129
|
+
"""Handler does not fire on budget exceeded errors."""
|
|
130
|
+
events = []
|
|
131
|
+
handler = PaymentCallbackHandler(
|
|
132
|
+
on_payment=lambda e: events.append(e),
|
|
133
|
+
)
|
|
134
|
+
|
|
135
|
+
handler.on_tool_end(
|
|
136
|
+
"Payment error: BudgetExceeded: per-request limit 500",
|
|
137
|
+
name="l402_fetch",
|
|
138
|
+
)
|
|
139
|
+
|
|
140
|
+
assert len(events) == 0
|
|
@@ -0,0 +1,111 @@
|
|
|
1
|
+
"""Tests for the create_l402_client factory function."""
|
|
2
|
+
|
|
3
|
+
import pytest
|
|
4
|
+
|
|
5
|
+
from l402 import Budget, L402Client
|
|
6
|
+
|
|
7
|
+
from l402_langchain import create_l402_client
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
class TestCreateL402Client:
|
|
11
|
+
"""Tests for the create_l402_client factory."""
|
|
12
|
+
|
|
13
|
+
def test_lnd_backend(self):
|
|
14
|
+
"""LND backend creates a working client."""
|
|
15
|
+
client = create_l402_client(
|
|
16
|
+
backend="lnd",
|
|
17
|
+
url="https://localhost:8080",
|
|
18
|
+
macaroon="deadbeef0123456789",
|
|
19
|
+
)
|
|
20
|
+
assert isinstance(client, L402Client)
|
|
21
|
+
|
|
22
|
+
def test_cln_backend(self):
|
|
23
|
+
"""CLN backend creates a working client."""
|
|
24
|
+
client = create_l402_client(
|
|
25
|
+
backend="cln",
|
|
26
|
+
url="https://localhost:3001",
|
|
27
|
+
rune="test_rune_token",
|
|
28
|
+
)
|
|
29
|
+
assert isinstance(client, L402Client)
|
|
30
|
+
|
|
31
|
+
def test_swissknife_backend(self):
|
|
32
|
+
"""SwissKnife backend creates a working client."""
|
|
33
|
+
client = create_l402_client(
|
|
34
|
+
backend="swissknife",
|
|
35
|
+
url="https://api.numeraire.tech",
|
|
36
|
+
api_key="sk-test-key",
|
|
37
|
+
)
|
|
38
|
+
assert isinstance(client, L402Client)
|
|
39
|
+
|
|
40
|
+
def test_lnd_with_dict_budget(self):
|
|
41
|
+
"""Dict budget is converted to Budget instance."""
|
|
42
|
+
client = create_l402_client(
|
|
43
|
+
backend="lnd",
|
|
44
|
+
url="https://localhost:8080",
|
|
45
|
+
macaroon="deadbeef0123456789",
|
|
46
|
+
budget={"per_request_max": 200, "daily_max": 1000},
|
|
47
|
+
)
|
|
48
|
+
assert isinstance(client, L402Client)
|
|
49
|
+
|
|
50
|
+
def test_lnd_with_budget_instance(self):
|
|
51
|
+
"""Budget instance is passed through directly."""
|
|
52
|
+
budget = Budget(per_request_max=200)
|
|
53
|
+
client = create_l402_client(
|
|
54
|
+
backend="lnd",
|
|
55
|
+
url="https://localhost:8080",
|
|
56
|
+
macaroon="deadbeef0123456789",
|
|
57
|
+
budget=budget,
|
|
58
|
+
)
|
|
59
|
+
assert isinstance(client, L402Client)
|
|
60
|
+
|
|
61
|
+
def test_lnd_missing_macaroon_raises(self):
|
|
62
|
+
"""Missing macaroon for LND raises ValueError."""
|
|
63
|
+
with pytest.raises(ValueError, match="macaroon"):
|
|
64
|
+
create_l402_client(
|
|
65
|
+
backend="lnd",
|
|
66
|
+
url="https://localhost:8080",
|
|
67
|
+
)
|
|
68
|
+
|
|
69
|
+
def test_cln_missing_rune_raises(self):
|
|
70
|
+
"""Missing rune for CLN raises ValueError."""
|
|
71
|
+
with pytest.raises(ValueError, match="rune"):
|
|
72
|
+
create_l402_client(
|
|
73
|
+
backend="cln",
|
|
74
|
+
url="https://localhost:3001",
|
|
75
|
+
)
|
|
76
|
+
|
|
77
|
+
def test_swissknife_missing_api_key_raises(self):
|
|
78
|
+
"""Missing api_key for SwissKnife raises ValueError."""
|
|
79
|
+
with pytest.raises(ValueError, match="api_key"):
|
|
80
|
+
create_l402_client(
|
|
81
|
+
backend="swissknife",
|
|
82
|
+
url="https://api.numeraire.tech",
|
|
83
|
+
)
|
|
84
|
+
|
|
85
|
+
def test_unsupported_backend_raises(self):
|
|
86
|
+
"""Unsupported backend raises ValueError."""
|
|
87
|
+
with pytest.raises(ValueError, match="Unsupported backend"):
|
|
88
|
+
create_l402_client(
|
|
89
|
+
backend="nwc",
|
|
90
|
+
url="https://localhost:8080",
|
|
91
|
+
)
|
|
92
|
+
|
|
93
|
+
def test_invalid_budget_type_raises(self):
|
|
94
|
+
"""Non-dict, non-Budget budget raises TypeError."""
|
|
95
|
+
with pytest.raises(TypeError, match="budget must be"):
|
|
96
|
+
create_l402_client(
|
|
97
|
+
backend="lnd",
|
|
98
|
+
url="https://localhost:8080",
|
|
99
|
+
macaroon="deadbeef",
|
|
100
|
+
budget="invalid", # type: ignore[arg-type]
|
|
101
|
+
)
|
|
102
|
+
|
|
103
|
+
def test_custom_max_fee_sats(self):
|
|
104
|
+
"""Custom max_fee_sats is accepted."""
|
|
105
|
+
client = create_l402_client(
|
|
106
|
+
backend="lnd",
|
|
107
|
+
url="https://localhost:8080",
|
|
108
|
+
macaroon="deadbeef0123456789",
|
|
109
|
+
max_fee_sats=50,
|
|
110
|
+
)
|
|
111
|
+
assert isinstance(client, L402Client)
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
"""Tests for L402FetchTool and L402BudgetTool.
|
|
2
|
+
|
|
3
|
+
Constructor and metadata tests work without a real Lightning backend.
|
|
4
|
+
Tests that require actual L402 responses are marked as regtest tests
|
|
5
|
+
and skipped when the regtest environment is not available.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
import json
|
|
9
|
+
|
|
10
|
+
import pytest
|
|
11
|
+
|
|
12
|
+
from l402 import L402Client
|
|
13
|
+
from l402_langchain import L402BudgetTool, L402FetchTool
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
class TestL402FetchToolMetadata:
|
|
17
|
+
"""Tests for L402FetchTool metadata and construction."""
|
|
18
|
+
|
|
19
|
+
def test_tool_metadata(self, client_setup):
|
|
20
|
+
"""Tool has correct name and description for LangChain."""
|
|
21
|
+
tool = L402FetchTool(client=client_setup["client"])
|
|
22
|
+
|
|
23
|
+
assert tool.name == "l402_fetch"
|
|
24
|
+
assert "L402" in tool.description
|
|
25
|
+
assert "Lightning" in tool.description
|
|
26
|
+
|
|
27
|
+
def test_constructor_accepts_client(self, client_setup):
|
|
28
|
+
"""Tool can be constructed with an L402Client."""
|
|
29
|
+
tool = L402FetchTool(client=client_setup["client"])
|
|
30
|
+
assert tool is not None
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
class TestL402BudgetToolMetadata:
|
|
34
|
+
"""Tests for L402BudgetTool metadata and construction."""
|
|
35
|
+
|
|
36
|
+
def test_tool_metadata(self, client_setup):
|
|
37
|
+
"""Tool has correct name and description."""
|
|
38
|
+
tool = L402BudgetTool(client=client_setup["client"])
|
|
39
|
+
|
|
40
|
+
assert tool.name == "l402_check_budget"
|
|
41
|
+
assert "spent" in tool.description.lower()
|
|
42
|
+
|
|
43
|
+
def test_no_payments(self, client_setup):
|
|
44
|
+
"""Reports zero spending when no payments made."""
|
|
45
|
+
tool = L402BudgetTool(client=client_setup["client"])
|
|
46
|
+
result = tool.invoke("")
|
|
47
|
+
|
|
48
|
+
assert "No payments made yet" in result
|
|
49
|
+
assert "0 sats" in result
|