Intelligent Agents with Bitcoin

in #bitcoin8 years ago

 

Overview

This tutorial will introduce you to the concept of bitcoin-powered intelligent agents. You'll learn how a client can use bitcoin to outsource a large computation to a server, and build your first intelligent agent. Specifically, here are the steps you will follow:  

  • First, you will set up a bitcoin-payable API server
  • Then, you will set up a client with some bitcoin
  • Your client will then spend bitcoin to buy an API call from the server, speeding up a local computation
  • You will then set up a second bitcoin-payable API server at a different price, and modify your client to buy from the lowest-priced bidder in realtime - thus creating an intelligent agent.

Once you’ve gone through those steps, you will start to see how bitcoin can be used as a lubricant for machine-to-machine transactions and a powerful way to monetize spare computer time. 

Prerequisites

You will need the following first:  

If you've got all the prerequisites, you are ready to go. Let's get started! 

Step 1: Set up a bitcoin-accelerated computing endpoint

You should go through all the steps in the Bitcoin Accelerated Computing tutorial. In particular, you should have the server1.py code running. 

Step 2: Add a competitor endpoint-provider to the market

Open a new terminal window. If you use a 21 Bitcoin Computer, ssh into it: 

## Only necessary if you use a 21 Bitcoin Computer
ssh twenty@IP_ADDRESS

Now we will set up a second merchant server to sell the same endpoint for bitcoin. Create a folder to house the server project: 

mkdir bitcoin-aware-computing-server2 && cd bitcoin-aware-computing-server2

Then create a new file that we'll call server2.py and add the same code you added earlier to the server1.py file for the Bitcoin-Accelerated Computing. We will only change the part that the server is hosting the endpoints on, and the price the merchant will offer the endpoint for: 

#!/usr/bin/env python3
import json

from flask import Flask, request

from two1.wallet import Wallet
from two1.bitserv.flask import Payment

app = Flask(__name__)
wallet = Wallet()
payment = Payment(app, wallet)


# sort method w/out delay simulates faster computation server
def fast_get_element(arr, prop, val):
    for elem in arr:
        if elem[prop] == val:
            return elem


def get_array_to_sort(request):
    return json.loads(request.form.getlist("array")[0])


@app.route('/fastfind', methods=['GET', 'POST'])
@payment.required(3000)
def fast_get_elem():
    arr = get_array_to_sort(request)
    prop = request.form.getlist("property")[0]
    value = int(request.form.getlist("value")[0])
    res = fast_get_element(arr, prop, value)
    return json.dumps({"elem": str(res)})

# set up and run the server
if __name__ == '__main__':
    app.run(host='0.0.0.0', port=9000)

Start your second micropayments server: 

python3 server2.py

Step 3: Create an intelligent agent that searches for the lowest-priced API

Now that we have two endpoints for this paid API, we have a market. And so we can write an intelligent agent that asks several merchant servers in the market for the price of the endpoint they are hosting, and then chooses the cheapest one. Open another new terminal window. If you use a 21 Bitcoin Computer, ssh into it: 

## Only necessary if you use a 21 Bitcoin Computer
ssh twenty@IP_ADDRESS

Add the following code to the client.py script that was created when running the Bitcoin-Accelerated Computing demo: 

#!/usr/bin/env python3
import json

from two1.commands.config import Config
from two1.wallet import Wallet
from two1.bitrequests import BitTransferRequests

# set up bitrequest client for BitTransfer requests
wallet = Wallet()
username = Config().username
requests = BitTransferRequests(wallet, username)

# sample data
data = [
    {'height': 4},
    {'height': 3},
    {'height': 6},
    {'height': 4},
    {'height': 3},
    {'height': 6},
    {'height': 4},
    {'height': 3},
    {'height': 6},
    {'height': 10},
]


def main():
    # Compare prices for two merchant servers hosting the same endpoint,
    # and purchase the cheaper one
    response1 = requests.get_402_info(url='http://localhost:5000/fastfind')
    endpoint_info1 = dict(response1)

    response2 = requests.get_402_info(url='http://localhost:9000/fastfind')
    endpoint_info2 = dict(response2)

    print("Merchant 1 Price: " + str(endpoint_info1))
    print("Merchant 2 Price: " + str(endpoint_info2))

    price1 = endpoint_info1['price']
    price2 = endpoint_info2['price']

    body = {
        'array': json.dumps(data),
        'property': 'height',
        'value': 10
    }

    if int(price1) < int(price2):
        # purchase from merchant 1
        res = requests.post(url='http://localhost:5000/fastfind', data=body)
    else:
        # purchase from merchant 2
        res = requests.post(url='http://localhost:9000/fastfind', data=body)
    answer = json.loads(res.text)['elem']
    print(answer)

if __name__ == '__main__':
    main()

Example Output: 

Merchant 1 Price: {'price': '3000', 'bitcoin-address': '14nfTDNfmQHTfxtYKwUAa5PbrB7hZqTvHu', 'username': 'testuser1'}
Merchant 2 Price: {'price': '4000', 'bitcoin-address': '19ZSKGwL21nNo2kTger5ciM1xYrzNJcCRY', 'username': 'testuser2'}

Since it looks like Merchant 1 is currently offering this API call at a better rate, so we purchased that endpoint: 

{'height': 10}

That's it! You just built your first intelligent agent, a program capable of getting price quotes in BTC from two servers and buying the lowest priced item. 

Next Steps

Along with micropayments, the technology industry has wanted true intelligent agents (IAs) since the beginning of the World Wide Web. One of the things that has hampered the development of IAs is the extraordinarily wide assortment of different kinds of credit card forms and payment methods on different websites. Some sites accept Paypal, others Stripe, and still others Alipay. And all sites have different checkout flows and lists of accepted currencies. Bitcoin promises to change that. Certainly not all at once, and not for all legacy sites. But at least for HTTP-accessible digital goods and services, it makes sense to make them bitcoin-payable given how easy that now is to do. And once they are bitcoin-payable, then they can be scraped and purchased by an intelligent agent, as the code shows above. As a next step, try passing in a function which takes a request instance and returns a price into the payment.required decorator in lieu of a fixed price. Specifically, try modifying the example such that each server uses a pricing function where the price oscillates sinusoidally. Now run your intelligent agent over and over again and watch it pick the lower of the two prices each time. Once you've done that, things start to get really interesting if you have N clients and M servers for the same digital good, with finite or rate-limited supply. Then you have a digital marketplace. If you build anything like this and want to earn some bitcoin for your efforts, write it up and submit it as a bitcoin tutorial. If we decide to publish it on our site, you'll win $200 in BTC! You can also come to our Slack channel at slack.21.co to find other 21 users to post your endpoints and give feedback. We look forward to seeing you there!   

How to send your Bitcoin to the Blockchain

Just as a reminder, you can send bitcoin mined or earned in your 21.co balance to the blockchain at any time by running 21 flush . A transaction will be created within 10 minutes, and you can view the transaction id with 21 log. Once the transaction has been confirmed, you can check the balance in your bitcoin wallet from the command line with wallet balance, and you can send bitcoin from your wallet to another address with wallet sendto $BITCOIN_ADDRESS --satoshis $SATOSHI_AMOUNT --use-unconfirmed. The --satoshis flag allows you to specify the amount in satoshis; without it the sendto amount is in BTC, but this behavior is deprecated and will be removed soon. The --use-unconfirmed flag ensures that you can send even if you have unconfirmed transactions in your wallet.   

Ready to sell your endpoint? Go to slack.21.co

Ready to try out your bitcoin-payable server in the wild? Or simply want to browse and purchase from other bitcoin-enabled servers? Head over to the 21 Developer Community at slack.21.co to join the bitcoin machine-payable marketplace hosted on the 21 peer-to-peer network.     

Next :

Learn the 21 tools, and start building your first Bitcoin App! 

     Author(s)
John Granata This content is licensed under a Creative Commons Attribution-ShareAlike 4.0 International License.    

https://21.co/learn/intelligent-agents-with-bitcoin/#next-steps