from fewsats.core import *
fewsats
This library enables AI agents to handle real-world payments autonomously. It provides a simple interface for AI systems to manage payment methods, process transactions, and interact with L402 paywalls.
The library provides two main interfaces: 1. Direct payment handling through the Python SDK 2. AI-native tools through as_tools()
for autonomous agents
Install
Install latest from pypi
$ pip install fewsats
Getting Started
The library provides a Fewsats
class to handle payments. You can use handle them manually or use the as_tools()
method to create tools for autonomous agents.
Making Payments
Obtain information about your account and perform payments:
= Fewsats()
fs import os
= Fewsats(api_key=os.getenv("FEWSATS_LOCAL_API_KEY"), base_url='http://localhost:8000')
fs fs.payment_methods().json(), fs.balance().json(), fs.me().json()
([{'id': 1,
'last4': '4242',
'brand': 'visa',
'exp_month': 12,
'exp_year': 2034,
'is_default': False},
{'id': 4,
'last4': '4242',
'brand': 'Visa',
'exp_month': 12,
'exp_year': 2034,
'is_default': True}],
[{'id': 1, 'balance': 4464, 'currency': 'usd'}],
{'name': 'Pol',
'last_name': 'Alvarez Vecino',
'email': 'pol@fewsats.com',
'billing_info': None,
'id': 1,
'created_at': '2024-08-20T16:13:01.255Z',
'webhook_url': 'https://example.com/webhook'})
The pay
method uses the information returned by a L402 Protocol 402 Payment Required
response to submit a payment. The L402 flow is handled by the backend. By default it will also choose the most convenient payment method, and assume you want to pay the first offer if multiple are available.
# Example offer from stock.l402.org
= {
l402_offer "offers":[
{"amount":1,
"balance":1,
"currency":"USD",
"description":"Purchase 1 credit for API access",
"offer_id":"offer_c668e0c0",
"payment_methods":[
"lightning"
],"title":"1 Credit Package",
"type":"top-up"
}
],"payment_context_token":"edb53dec-28f5-4cbb-924a-20e9003c20e1",
"payment_request_url":"https://stock.l402.org/l402/payment-request",
"terms_url":"https://link-to-terms.com",
"version":"0.2.1"
}
fs.pay_offer(l402_offer).json()
{'id': 121,
'created_at': '2025-02-10T11:04:48.083Z',
'status': 'success',
'payment_method': 'lightning'}
Fewsats also supports paying for resources like a lightning invoice directly. For example:
fs.pay_lightning(invoice='lnbc100n1pn6fsyspp5g2f6hdqxc76wxccq2cd4wekck0nxfucfyvzkvy9fmxezlf3hcl6qdqqcqzpgxqyz5vqrzjqwghf7zxvfkxq5a6sr65g0gdkv768p83mhsnt0msszapamzx2qvuxqqqqz99gpz55yqqqqqqqqqqqqqq9qrzjq25carzepgd4vqsyn44jrk85ezrpju92xyrk9apw4cdjh6yrwt5jgqqqqz99gpz55yqqqqqqqqqqqqqq9qsp5yzvs9czquyf8mjgwf465k0a7g4vh7jqv2cpza3lkygnllxnzk2wq9qxpqysgqnkmhmw05q6qc8urah004jtnkuztpazgg49m3g2wfamexr0m0ayrhla2ephnsm0xan3pweqc3hexeqx2mkfr8d3afwx6rds2r2znf4vgq7new3k',
amount=1, currency='USD', description='Purchase 1 cent for API access')
<Response [200 OK]>
The lightning invoice already contains a payment amount, but the method requires you to specify the amount you are expecting to pay in cents. This is done for accounting purposes and convenience, but the amount paid will be the sats in the invoice.
Getting Paid
Fewsats also provides methods for receiving payments. You can create offers for receiving payments as follows.
# Create offers for receiving payments
= [{
offers_data "offer_id": "offer_example",
"amount": 1,
"currency": "USD",
"description": "Receive payment for your service",
"title": "1 Credit Package",
"payment_methods": ["lightning", "stripe"]
}]= fs.create_offers(offers_data)
r = r.json()
offers offers
{'offers': [{'offer_id': 'offer_example',
'amount': 1,
'currency': 'USD',
'description': 'Receive payment for your service',
'title': '1 Credit Package',
'payment_methods': ['lightning', 'stripe'],
'type': 'one-off'}],
'payment_context_token': 'a175fd73-cb68-4a22-8685-b236eff2f1a0',
'payment_request_url': 'http://localhost:8000/v0/l402/payment-request',
'version': '0.2.2'}
You can check if an offer has been paid using the payment context token as follows.
=offers["payment_context_token"]).json() fs.get_payment_status(payment_context_token
{'payment_context_token': 'a175fd73-cb68-4a22-8685-b236eff2f1a0',
'status': 'pending',
'offer_id': None,
'paid_at': None,
'amount': None,
'currency': None}
If you prefer to be notified whenever an offer is paid, you can set up a webhook as follows, and we will call it whenever a payment is made.
= fs.set_webhook(webhook_url="https://example.com/webhook")
r r.json()
{'name': 'Pol',
'last_name': 'Alvarez Vecino',
'email': 'pol@fewsats.com',
'billing_info': None,
'id': 1,
'created_at': '2024-08-20T16:13:01.255Z',
'webhook_url': 'https://example.com/webhook'}
AI Agent Integration
We will show how to enable your AI assistant to handle payments using Claudette, Answer.ai convenient wrapper for Claude. You’ll need to export your ANTHROPIC_API_KEY
as env variable for this to work.
from claudette import Chat, models
import os
# os.environ['ANTHROPIC_LOG'] = 'debug'
= models[1]; model model
'claude-3-5-sonnet-20240620'
To print every HTTP request and response in full, uncomment the above line.
fs.balance()
[{'id': 15, 'balance': 5963, 'currency': 'usd'}]
= Chat(model, sp='You are a helpful assistant that can pay offers.', tools=fs.as_tools())
chat = f"Could you pay the cheapest offer using lightning {l402_offer}?"
pr = chat.toolloop(pr, trace_func=print)
r r
Message(id='msg_01P2WhNQy4r7pTdqeLhv25uo', content=[TextBlock(text="Certainly! I can help you pay for the cheapest offer using Lightning. Based on the information you've provided, there's only one offer available, so we'll proceed with that one. Let's use the `pay` function to complete this transaction.\n\nFirst, let's organize the information we have:\n\n1. There's one offer for 1 credit at $0.01 (1 cent).\n2. The payment method is Lightning.\n3. We have a payment context token and a payment request URL.\n\nNow, let's call the `pay` function with the required parameters:", type='text'), ToolUseBlock(id='toolu_01KqP7nL9J48keGPJoPS2yGf', input={'purl': 'https://stock.l402.org/l402/payment-request', 'pct': 'edb53dec-28f5-4cbb-924a-20e9003c20e1', 'amount': 1, 'balance': 1, 'currency': 'USD', 'description': 'Purchase 1 credit for API access', 'offer_id': 'offer_c668e0c0', 'payment_methods': ['lightning'], 'title': '1 Credit Package', 'type': 'top-up'}, name='pay', type='tool_use')], model='claude-3-5-sonnet-20240620', role='assistant', stop_reason='tool_use', stop_sequence=None, type='message', usage=In: 1002; Out: 395; Cache create: 0; Cache read: 0; Total: 1397)
Message(id='msg_01Tm57TAVcqN4Gh1dV7NdR4b', content=[TextBlock(text="Great news! The payment has been successfully processed. Here's a summary of the transaction:\n\n1. Payment Status: Success\n2. Amount Paid: 1 cent (USD)\n3. Payment Method: Lightning\n4. Title: 1 Credit Package\n5. Description: Purchase 1 credit for API access\n6. Type: Top-up\n7. Transaction ID: 253\n8. Created At: 2024-12-26T15:21:23.413Z\n\nThe payment has been completed successfully using the Lightning network. You should now have 1 credit added to your API access. Is there anything else you'd like to know about this transaction or any other assistance you need?", type='text')], model='claude-3-5-sonnet-20240620', role='assistant', stop_reason='end_turn', stop_sequence=None, type='message', usage=In: 1952; Out: 156; Cache create: 0; Cache read: 0; Total: 2108)
Great news! The payment has been successfully processed. Here’s a summary of the transaction:
- Payment Status: Success
- Amount Paid: 1 cent (USD)
- Payment Method: Lightning
- Title: 1 Credit Package
- Description: Purchase 1 credit for API access
- Type: Top-up
- Transaction ID: 253
- Created At: 2024-12-26T15:21:23.413Z
The payment has been completed successfully using the Lightning network. You should now have 1 credit added to your API access. Is there anything else you’d like to know about this transaction or any other assistance you need?
- id:
msg_01Tm57TAVcqN4Gh1dV7NdR4b
- content:
[{'text': "Great news! The payment has been successfully processed. Here's a summary of the transaction:\n\n1. Payment Status: Success\n2. Amount Paid: 1 cent (USD)\n3. Payment Method: Lightning\n4. Title: 1 Credit Package\n5. Description: Purchase 1 credit for API access\n6. Type: Top-up\n7. Transaction ID: 253\n8. Created At: 2024-12-26T15:21:23.413Z\n\nThe payment has been completed successfully using the Lightning network. You should now have 1 credit added to your API access. Is there anything else you'd like to know about this transaction or any other assistance you need?", 'type': 'text'}]
- model:
claude-3-5-sonnet-20240620
- role:
assistant
- stop_reason:
end_turn
- stop_sequence:
None
- type:
message
- usage:
{'cache_creation_input_tokens': 0, 'cache_read_input_tokens': 0, 'input_tokens': 1952, 'output_tokens': 156}
fs.balance()
[{'id': 15, 'balance': 5962, 'currency': 'usd'}]