Giter Site home page Giter Site logo

mech-client's Introduction

Mech Client

A basic client to interact with an AI Mech. AI Mechs allow users to post requests for AI tasks on-chain, and get their result delivered.

⚠️ Warning
This is a hacky alpha version of the client. Don't rely on it as production software.

Requirements

  • Python >=3.10

Installation

Find the latest available release on PyPi.

We recommend that you create a virtual Python environment using Poetry. Set up your virtual environment as follows:

poetry new my_project
cd my_project
poetry shell
poetry add mech-client

Alternatively, you can also install the Mech Client in your local Python installation:

pip install mech-client

If you require to use the Mech Client programmatically, please see this section below.

CLI Usage

Display the available options:

mechx --help
Usage: mechx [OPTIONS] COMMAND [ARGS]...

  Command-line tool for interacting with mechs.

Options:
  --version  Show the version and exit.
  --help     Show this message and exit.

Commands:
  interact        Interact with a mech specifying a prompt and tool.
  prompt-to-ipfs  Upload a prompt and tool to IPFS as metadata.
  push-to-ipfs    Upload a file to IPFS.
  to-png          Convert a stability AI API's diffusion model output...

Set up the EOA and private key

To use the Mech Client you need an EOA account and its associated private key stored in a text file ethereum_private_key.txt. You can set it up in two ways:

  • Use any software of your choice (e.g., Metamask) and copy the private key:

    echo -n YOUR_PRIVATE_KEY > ethereum_private_key.txt

    Do not include any leading or trailing spaces, tabs or newlines, or any other character in the file ethereum_private_key.txt.

  • Alternatively, use the Open AEA command generate-key (you'll need to install Open AEA and its Ethereum ledger plugin):

    aea generate-key ethereum

    and display the corresponding EOA:

    python -c "from web3 import Web3; print(Web3().eth.account.from_key(open('ethereum_private_key.txt').read()).address)"

The EOA you use must have enough funds to pay for the Mech requests, or alternatively, use a Nevermined subscription.

⚠️ Warning

  • If the generated EOA account is for development purposes, make sure it does not contain large amounts of funds.

  • If you store the key file in a local Git repository, we recommend that you add it to .gitignore in order to avoid publishing it unintentionally:

    echo ethereum_private_key.txt >> .gitignore

Select the mech you are going to send requests to

Mechs are deployed to several networks. Find the list of supported networks and corresponging mech addresses here.

Generate Mech requests

The basic usage of the Mech Client is as follows:

mechx interact <prompt> <agent_id>

where agent with <agent_id> will process <prompt> with the default options. Each chain has its own set of Mech agents. You can find the agent IDs for each chain on the Mech Hub or on the Mech repository.

Some useful options:

  • --key <private_key_path>: Specifies the path of the private key. The default value is ./ethereum_private_key.txt.

  • --tool <name>: Name of the tool to process the prompt. If you are aware about the tools that are provided by an agent you can directly provide its name using this option. If not provided, it will show a list of available tools for the agent so that you can select which one you want to use:

    Select prompting tool
    |--------------------------------------------------|
    | ID | Tool                                        |
    |--------------------------------------------------|
    | 0  | openai-text-davinci-002                     |
    | ...| ...                                         |
    |--------------------------------------------------|
    Tool ID >
    
  • --chain-config <name>: Use default chain configuration parameters (RPC, WSS, ...). See below for more details. Available values are

    • arbitrum
    • base
    • celo
    • gnosis (Default)
    • optimism
    • polygon
  • --confirm <type>: Specify how to wait for the result of your request:

    • off-chain: Wait for the result using the ACN.
    • on-chain: Wait for the result using the Subgraph and the Websocket subscription (whichever arrives first).
    • wait-for-both (Default): Wait for the result using both off-chain and on-chain (whichever arrives first).

Example

Example of a request specifying a key file and tool:

mechx interact "write a short poem" 6 --key ~/ethereum_private_key.txt --tool openai-gpt-3.5-turbo --chain-config gnosis --confirm on-chain

You will see an output like this:

Chain configuration: gnosis
Prompt uploaded: https://gateway.autonolas.tech/ipfs/f01701220af9e4e8b4bd62d76394064f493081917bcc0b9c34a4aff60f82623b717617279
Transaction sent: https://gnosisscan.io/tx/0x61359f9cc6a1debb07d34ce1038f6aa30d25257c17edeb2b161741805e43e8d0
Waiting for transaction receipt...
Created on-chain request with ID 100407405856633966395081711430940962809568685031934329025999216833965518452765
Data arrived: https://gateway.autonolas.tech/ipfs/f01701220a462120d5bb03f406fa5ef3573df77184a20ab6343d7bade76bd321654aa7251
Data from agent: {'requestId': 100407405856633966395081711430940962809568685031934329025999216833965518452765, 'result': "In a world of chaos and strife,\nThere's beauty in the simplest of life.\nA gentle breeze whispers through the trees,\nAnd birds sing melodies with ease.\n\nThe sun sets in a fiery hue,\nPainting the sky in shades of blue.\nStars twinkle in the darkness above,\nGuiding us with their light and love.\n\nSo take a moment to pause and see,\nThe wonders of this world so free.\nEmbrace the joy that each day brings,\nAnd let your heart soar on gentle wings.", 'prompt': 'write a short poem', 'cost_dict': {}, 'metadata': {'model': None, 'tool': 'openai-gpt-3.5-turbo'}}

✏️ Note
If you encounter an "Out of gas" error when executing the Mech Client, you will need to increase the gas limit, e.g.,

export MECHX_GAS_LIMIT=200000

Chain configuration

Default configurations for different chains are stored in the file configs/mechs.json. If --chain-config parameter is not specified, the Mech Client will choose the first configuration on the JSON.

Additionally, you can override any configuration parameter by exporting any of the following environment variables:

MECHX_CHAIN_RPC
MECHX_WSS_ENDPOINT
MECHX_GAS_LIMIT
MECHX_CONTRACT_ABI_URL
MECHX_TRANSACTION_URL
MECHX_SUBGRAPH_URL

MECHX_LEDGER_ADDRESS
MECHX_LEDGER_CHAIN_ID
MECHX_LEDGER_POA_CHAIN
MECHX_LEDGER_DEFAULT_GAS_PRICE_STRATEGY
MECHX_LEDGER_IS_GAS_ESTIMATION_ENABLED

Programmatic usage

You can also use the Mech Client as a library on your Python project.

  1. Set up the private key as specified above. Store the resulting key file (e.g., ethereum_private_key.txt) in a convenient and secure location.

  2. Create Python script my_script.py:

    touch my_script.py
  3. Edit my_script.py as follows:

    from mech_client.interact import interact, ConfirmationType
    
    prompt_text = 'Will Gnosis pay reach 100k cards in 2024?'
    agent_id = 6
    tool_name = "prediction-online"
    chain_config = "gnosis"
    private_key_path="ethereum_private_key.txt"
    
    result = interact(
        prompt=prompt_text,
        agent_id=agent_id,
        tool=tool_name,
        chain_config=chain_config,
        confirmation_type=ConfirmationType.ON_CHAIN,
        private_key_path=private_key_path
    )
    print(result)

Developer installation

To setup the development environment for this project, clone the repository and run the following commands:

poetry install
poetry shell

Release guide

  • Bump versions in pyproject.toml.mech_client/__init__.py and SECURITY.md
  • poetry lock
  • rm -rf dist
  • autonomy packages sync --update-packages
  • make eject-packages
  • Then, create a release PR and tag the release.

FAQ

On which chains are AI Mechs deployed?

The Mech repository contains the latest information on deployed Mechs.

Are AI Mechs deployed on testnets?

No. AI Mechs are currently deployed only on mainnets.

Where can I find the agent ID?

You can find the agent IDs for each chain on the Mech Hub or on the Mech repository.

How do I access an AI Mech on a different chain?

Use the --chain-config <name> parameter together with a valid <agent_id>, for example:

mechx interact "write a short poem" 2 --key ./ethereum_private_key.txt --tool openai-gpt-4 --chain-config celo --confirm on-chain

mech-client's People

Contributors

angrybayblade avatar jmoreira-valory avatar davidminarsch avatar adamantios avatar 0xardi avatar dvilelaf avatar gigahierz avatar kongzii avatar

Stargazers

Gabriel Temsten avatar Gabriel Fior avatar

Watchers

 avatar  avatar arshy avatar  avatar

mech-client's Issues

Can't find the address related to the private key created with the open-aea library

When I am trying to get the address related to the private key created in ethereum_private_key.txt to fund it on Gnosis Chain I am getting an error message,

I have tried to aea get-address ethereum and aea get-public-key ethereum

Error message:

Error: Agent configuration file 'aea-config.yaml' not found in the current directory.

mech_client.interact.interact example not working

If I try the simple example:

from mech_client.interact import ConfirmationType, interact

result = interact(
    prompt="Why is the sky blue?",
    confirmation_type=ConfirmationType.ON_CHAIN,
    agent_id=3,
    private_key_path="./private_key.txt",
    tool="prediction-online",
)

And execute it, I get an error:

% WEBSOCKET_ENDPOINT=wss://rpc.gnosischain.com/wss python example.py
Prompt uploaded: https://gateway.autonolas.tech/ipfs/f01701220df93b1063813298b990f21cd2bf8dfded593d7355ea75cd57423c62cd916ee84
Unable to estimate gas with default state , ContractCustomError: System.ArgumentException: Expected a positive number and got -16594444 (Parameter 'a')
   at Nethermind.JsonRpc.Modules.Eth.EthRpcModule.TxExecutor`1.ExecuteTx(TransactionForRpc transactionCall, BlockParameter blockParameter) in /_/src/Nethermind/Nethermind.JsonRpc/Modules/Eth/EthRpcModule.TransactionExecutor.cs:line 39
   at InvokeStub_IEthRpcModule.eth_estimateGas(Object, Span`1)
   at System.Reflection.MethodBaseInvoker.InvokeWithFewArgs(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
Error occured while sending the transaction: System.ArgumentException: Expected a positive number and got -16594444 (Parameter 'a')
   at Nethermind.JsonRpc.Modules.Eth.EthRpcModule.TxExecutor`1.ExecuteTx(TransactionForRpc transactionCall, BlockParameter blockParameter) in /_/src/Nethermind/Nethermind.JsonRpc/Modules/Eth/EthRpcModule.TransactionExecutor.cs:line 39
   at InvokeStub_IEthRpcModule.eth_estimateGas(Object, Span`1)
   at System.Reflection.MethodBaseInvoker.InvokeWithFewArgs(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture); Retrying in 3.0

Mech client hangs with `ConfirmationType.OFF_CHAIN`

The interact method does not return with confirmation_type == ConfirmationType.OFF_CHAIN

In stdout I see

Created on-chain request with ID 56439741347897565096390923836077361339766652372962787639228859560995999907820
Waiting for Mech response...

but in the mech web UI here I can see that the request matching that ID has a corresponding response (i.e. an. IPFS link)

To reproduce:

from mech_client.interact import ConfirmationType, interact

private_key_path = "..."

def _interact(confirmation_type: ConfirmationType):
    interact(
        prompt="Is the sky blue?",
        # Taken from https://github.com/valory-xyz/mech?tab=readme-ov-file#examples-of-deployed-mechs
        agent_id=6,
        private_key_path=private_key_path,
        tool="prediction-offline",
        confirmation_type=confirmation_type,
    )


_interact(ConfirmationType.WAIT_FOR_BOTH)  # works fine
_interact(ConfirmationType.OFF_CHAIN)  # hangs

mechx interact throws error for agent 1

Following the README, I tried fetching data from agent_id 1 on Gnosis
https://aimechs.autonolas.network/mech/0x3504fb5053ec12f748017248a395b4ed31739705/0x714ef7dafa358c7152f6703dd764a1df40d369dcf53275dd2543b0fdbf207298

however I get an error

:~/code/gnosis/mech-client-test$ mechx interact  "Tell me a joke" 1
Chain configuration: gnosis
Traceback (most recent call last):
  File "/home/gabrielfior/miniconda3/envs/mech-client/bin/mechx", line 8, in <module>
[...]
  File "/home/gabrielfior/miniconda3/envs/mech-client/lib/python3.10/site-packages/mech_client/interact.py", line 298, in verify_or_retrieve_tool
    available_tools = fetch_tools(
  File "/home/gabrielfior/miniconda3/envs/mech-client/lib/python3.10/site-packages/mech_client/interact.py", line 327, in fetch_tools
    return response["tools"]
KeyError: 'tools'

I debugged this a bit and found a possible cause - if you look at the agent definition for agent_id 6 (link), you see a tools key, whereas agent_id 1 doesn't have tools in its definition (link).

When I run the code above for agent_id 6, the prompt gets uploaded to IPFS (link below).

Relevant links:
-> Prompt generated for interaction with agent 6 - https://gateway.autonolas.tech/ipfs/f01701220a3901882dc60880c2e8538626f91f57125fdbbe44d6f6ec1c626801b82874512
-> Transaction created for fulfilling the request (failed because it ran out of gas) - https://gnosisscan.io/tx/0x465cddd037733073a1cb4c14abd9c54ac80695f970f53ffd5a47db9fa01a65ea

Client does not handle failed txs

After sending a request that ended with an out of gas error:

(mech-py3.10) david@XPS13:/tmp/mech$ mechx interact "write a short poem" 6 --key ~/ethereum_private_key.txt --tool openai-gpt-3.5-turbo --chain-config gnosis --confirm on-chain
Chain configuration: gnosis
Sending request...
Prompt uploaded: https://gateway.autonolas.tech/ipfs/f01701220f47c53331ec0fe34e4ed95614253caeeec8bdd012d9ddd0350d7a5f508b02b00
Transaction sent: https://gnosisscan.io/tx/0x316dc61917e9ee2940f41e29c71ace6012415ae38e9943958e3768f1b32d3b5c
Waiting for transaction receipt...

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.