From b7b7fb182936fd4a0bd8e1016ff1c3b8bbb092ac Mon Sep 17 00:00:00 2001 From: Felix Nicolae Bucsa Date: Thu, 17 Oct 2024 14:31:24 +0100 Subject: [PATCH] edits: fixed conflicts and added missing code blocks --- .github/spelling/known_words_corpus.txt | 6 + pages/guides/agents/intermediate/mailbox.mdx | 103 +++- pages/guides/ai-engine-sdk/javascript.mdx | 3 +- pages/guides/ai-engine-sdk/python.mdx | 3 +- .../apis/agent-function-creation-apis.mdx | 2 +- pages/guides/apis/secret-management-apis.mdx | 2 +- .../cosmpy/use-cases/liquidity-pool.mdx | 3 +- .../cosmpy/use-cases/oracles.mdx | 559 +++++++++++------- .../use-cases/stake-auto-compounder.mdx | 3 +- .../cosmpy/use-cases/stake-optimizer.mdx | 3 +- .../cosmpy/use-cases/swap_automation.mdx | 2 +- .../cosmpy/use-cases/wallet-top-up.mdx | 3 +- .../CrewAI/creating-an-agent-with-crewai.mdx | 408 +++++++------ 13 files changed, 673 insertions(+), 427 deletions(-) diff --git a/.github/spelling/known_words_corpus.txt b/.github/spelling/known_words_corpus.txt index ced3a65b..7d4b693c 100644 --- a/.github/spelling/known_words_corpus.txt +++ b/.github/spelling/known_words_corpus.txt @@ -672,3 +672,9 @@ etc lifecycle screenshot docscode +richtext +bestmatches +gnews +newsrequest +v20 +servicefordungeons \ No newline at end of file diff --git a/pages/guides/agents/intermediate/mailbox.mdx b/pages/guides/agents/intermediate/mailbox.mdx index 0e1eb9fb..b99e065c 100644 --- a/pages/guides/agents/intermediate/mailbox.mdx +++ b/pages/guides/agents/intermediate/mailbox.mdx @@ -107,54 +107,93 @@ Once the agent is correctly retrieved, you will have to give it a **name**. When Let's update `alice` agent; `alice` will now print to console any message it receives, provided the message is of type `Message`. Remember that you need to provide the `AGENT_MAILBOX_KEY`, `SEED_PHRASE`, `name`, `seed` and `mailbox` parameters to correctly run this code: - ```py copy filename="mailbox_agent_updated.py" - from uagents import Agent, Context, Model + + + + - class Message(Model): - message: str + + ```py copy filename="mailbox_agent_updated.py" - AGENT_MAILBOX_KEY = "put_your_AGENT_MAILBOX_KEY_here" - SEED_PHRASE = "put_your_seed_phrase_here" + from uagents import Agent, Context, Model + + class Message(Model): + message: str + + AGENT_MAILBOX_KEY = "put_your_AGENT_MAILBOX_KEY_here" + SEED_PHRASE = "put_your_seed_phrase_here" + + # Now your agent is ready to join the agentverse! + agent = Agent( + name="alice", + seed=SEED_PHRASE, + mailbox=f"{AGENT_MAILBOX_KEY}@https://agentverse.ai", + ) + + @agent.on_message(model=Message, replies={Message}) + async def handle_message(ctx: Context, sender: str, msg: Message): + ctx.logger.info(f"Received message from {sender}: {msg.message}") + + + if __name__ == "__main__": + agent.run() + +``` + - # Now your agent is ready to join the agentverse! - agent = Agent( - name="alice", - seed=SEED_PHRASE, - mailbox=f"{AGENT_MAILBOX_KEY}@https://agentverse.ai", - ) + - @agent.on_message(model=Message, replies={Message}) - async def handle_message(ctx: Context, sender: str, msg: Message): - ctx.logger.info(f"Received message from {sender}: {msg.message}") - if __name__ == "__main__": - agent.run() - ``` ## Creating a second agent Let's create and run a second agent to message Alice every 3 seconds. You need to provide the `ALICE_ADDRESS`, `name` and `seed` parameters to correctly run this code: - ```py copy filename="test_agent.py" - - from uagents import Agent, Bureau, Context, Model - from datetime import datetime + + + + - class Message(Model): - message: str + + ```py copy filename="test_agent.py" - agent_2 = Agent(name="agent_2", seed="agent_2 recovery phrase", port=8001, endpoint="http://localhost:8001/submit") + from uagents import Agent, Bureau, Context, Model + from datetime import datetime + + + class Message(Model): + message: str + + + agent_2 = Agent(name="agent_2", seed="agent_2 recovery phrase", port=8001, endpoint="http://localhost:8001/submit") + + ALICE_ADDRESS = "add_address_of_alice_agent" + + + @agent_2.on_interval(period=3.0) + async def send_message(ctx: Context): + await ctx.send(ALICE_ADDRESS, Message(message=f"hello {datetime.today().date()}")) + + + if __name__ == "__main__": + agent.run() - ALICE_ADDRESS = "add_address_of_alice_agent" +``` + - @agent_2.on_interval(period=3.0) - async def send_message(ctx: Context): - await ctx.send(ALICE_ADDRESS, Message(message=f"hello {datetime.today().date()}")) + - if __name__ == "__main__": - agent.run() - ``` ## Testing diff --git a/pages/guides/ai-engine-sdk/javascript.mdx b/pages/guides/ai-engine-sdk/javascript.mdx index 61e3a058..044ee2d8 100644 --- a/pages/guides/ai-engine-sdk/javascript.mdx +++ b/pages/guides/ai-engine-sdk/javascript.mdx @@ -1,5 +1,5 @@ import { Callout } from 'nextra/components' -import { CodeGroup, CodeSegment, DocsCode, GithubCodeSegment } from "../../../../components/code"; +import { CodeGroup, CodeSegment, DocsCode, GithubCodeSegment } from "../../../components/code"; # AI-Engine Javascript SDk @@ -270,3 +270,4 @@ The following example demonstrates how to use the AI Engine SDK to interact with + diff --git a/pages/guides/ai-engine-sdk/python.mdx b/pages/guides/ai-engine-sdk/python.mdx index bd20c46a..f53d03ee 100644 --- a/pages/guides/ai-engine-sdk/python.mdx +++ b/pages/guides/ai-engine-sdk/python.mdx @@ -1,5 +1,5 @@ import { Callout } from 'nextra/components' -import { CodeGroup, CodeSegment, DocsCode, GithubCodeSegment } from "../../../../components/code"; +import { CodeGroup, CodeSegment, DocsCode, GithubCodeSegment } from "../../../components/code"; # AI-Engine Python SDk @@ -323,3 +323,4 @@ The following example demonstrates how to use the AI Engine SDK to interact with + diff --git a/pages/guides/apis/agent-function-creation-apis.mdx b/pages/guides/apis/agent-function-creation-apis.mdx index 56abe059..2c959e6e 100644 --- a/pages/guides/apis/agent-function-creation-apis.mdx +++ b/pages/guides/apis/agent-function-creation-apis.mdx @@ -1,4 +1,4 @@ -import { CodeGroup, CodeSegment, DocsCode, GithubCodeSegment } from "../../../../components/code"; +import { CodeGroup, CodeSegment, DocsCode, GithubCodeSegment } from "../../../components/code"; # Agents and Functions Creation using APIs diff --git a/pages/guides/apis/secret-management-apis.mdx b/pages/guides/apis/secret-management-apis.mdx index 1604acfa..14fde393 100644 --- a/pages/guides/apis/secret-management-apis.mdx +++ b/pages/guides/apis/secret-management-apis.mdx @@ -1,5 +1,5 @@ import { Callout } from 'nextra/components' -import { CodeGroup, CodeSegment, DocsCode, GithubCodeSegment } from "../../../../components/code"; +import { CodeGroup, CodeSegment, DocsCode, GithubCodeSegment } from "../../../components/code"; # Adding Secret to Agents using Agentverse APIs diff --git a/pages/guides/fetch-network/cosmpy/use-cases/liquidity-pool.mdx b/pages/guides/fetch-network/cosmpy/use-cases/liquidity-pool.mdx index 91222c93..f63f1520 100644 --- a/pages/guides/fetch-network/cosmpy/use-cases/liquidity-pool.mdx +++ b/pages/guides/fetch-network/cosmpy/use-cases/liquidity-pool.mdx @@ -1,4 +1,4 @@ -import { CodeGroup, CodeSegment, DocsCode, GithubCodeSegment } from "../../../../components/code"; +import { CodeGroup, CodeSegment, DocsCode, GithubCodeSegment } from "../../../../../components/code"; # Liquidity pool @@ -435,3 +435,4 @@ The overall script should be as follows: + diff --git a/pages/guides/fetch-network/cosmpy/use-cases/oracles.mdx b/pages/guides/fetch-network/cosmpy/use-cases/oracles.mdx index 2cfe22c6..506b9718 100644 --- a/pages/guides/fetch-network/cosmpy/use-cases/oracles.mdx +++ b/pages/guides/fetch-network/cosmpy/use-cases/oracles.mdx @@ -1,4 +1,4 @@ -import { CodeGroup, CodeSegment, DocsCode, GithubCodeSegment } from "../../../../components/code"; +import { CodeGroup, CodeSegment, DocsCode, GithubCodeSegment } from "../../../../../components/code"; # Oracles @@ -43,98 +43,174 @@ We initially need to download the binaries for both contracts, which can be done 2. We would then also require the following imports: - ```py copy - from time import sleep - import requests - from cosmpy.aerial.client import LedgerClient, NetworkConfig - from cosmpy.aerial.contract import LedgerContract - from cosmpy.aerial.faucet import FaucetApi - from cosmpy.aerial.wallet import LocalWallet - from cosmpy.crypto.address import Address - ``` + + + + + + + ```py copy filename="aerial_oracle.py" + + import argparse + from time import sleep + + import requests + + from cosmpy.aerial.client import LedgerClient, NetworkConfig + from cosmpy.aerial.contract import LedgerContract + from cosmpy.aerial.faucet import FaucetApi + from cosmpy.aerial.wallet import LocalWallet + from cosmpy.crypto.address import Address + +``` + + + + + 3. We then need to choose a data source for the coin price, the update interval, the decimal precision, and the decimal timeout for the oracle value: - ```py copy - COIN_PRICE_URL = ( - "https://api.coingecko.com/api/v3/simple/price?ids=fetch-ai&vs_currencies=usd" - ) - UPDATE_INTERVAL_SECONDS = 10 - ORACLE_VALUE_DECIMALS = 5 - DEFAULT_TIMEOUT = 60.0 - ``` + + + + -4. We then proceed and define a `_parse_commandline()` function by first importing the `argparse` module, which is a standard Python module for parsing command-line arguments: + + ```py copy filename="aerial_oracle.py" - ```py copy - def _parse_commandline(): - parser = argparse.ArgumentParser() - parser.add_argument( - "contract_path", help="The path to the oracle contract to upload" - ) - parser.add_argument( - "contract_address", - nargs="?", - type=Address, - help="The address of the oracle contract if already deployed", - ) - return parser.parse_args() - ``` + COIN_PRICE_URL = ( + "https://api.coingecko.com/api/v3/simple/price?ids=fetch-ai&vs_currencies=usd" + ) + UPDATE_INTERVAL_SECONDS = 10 + ORACLE_VALUE_DECIMALS = 5 + DEFAULT_TIMEOUT = 60.0 - This first creates an argument `parser` object. The `ArgumentParser` class provides a way to specify the arguments your script should accept and automatically generates help messages and error messages. We then use `add_argument()` to add a positional argument named `contract_path`. This argument is required and should be a path to the oracle contract that you want to upload. The help argument provides a description of what this argument does. We further add another positional argument named `contract_address`. This argument is optional (`nargs="?"` allows it to be omitted), and it should be of type `Address`. The `type` argument specifies the type of the argument. In this case, `Address` is a custom type or class used to represent addresses. The `help` argument provides a description of what this argument does. At the end, we parse the command-line arguments provided when the script is executed. It returns an object that contains the values of the parsed arguments. +``` + -5. We then need to proceed and define our `main()` function: + - ```py copy - def main(): - """Run main.""" - args = _parse_commandline() - wallet = LocalWallet.generate() - ledger = LedgerClient(NetworkConfig.fetchai_stable_testnet()) - faucet_api = FaucetApi(NetworkConfig.fetchai_stable_testnet()) +4. We then proceed and define a `_parse_commandline()` function by first importing the `argparse` module, which is a standard Python module for parsing command-line arguments: - wallet_balance = ledger.query_bank_balance(wallet.address()) + + + + - while wallet_balance < (10**18): - print("Providing wealth to wallet...") - faucet_api.get_wealth(wallet.address()) - wallet_balance = ledger.query_bank_balance(wallet.address()) + + ```py copy filename="aerial_oracle.py" - contract = LedgerContract(args.contract_path, ledger, address=args.contract_address) + def _parse_commandline(): + parser = argparse.ArgumentParser() + parser.add_argument( + "contract_path", help="The path to the oracle contract to upload" + ) + parser.add_argument( + "contract_address", + nargs="?", + type=Address, + help="The address of the oracle contract if already deployed", + ) + return parser.parse_args() - if not args.contract_address: - instantiation_message = {"fee": "100"} - contract.deploy(instantiation_message, wallet, funds="1atestfet") +``` + - print(f"Oracle contract deployed at: {contract.address}") + - grant_role_message = {"grant_oracle_role": {"address": wallet}} - contract.execute(grant_role_message, wallet).wait_to_complete() - print(f"Oracle role granted to address: {wallet}") - while True: - resp = requests.get(COIN_PRICE_URL, timeout=DEFAULT_TIMEOUT).json() - price = resp["fetch-ai"]["usd"] - value = int(price * 10**ORACLE_VALUE_DECIMALS) + This first creates an argument `parser` object. The `ArgumentParser` class provides a way to specify the arguments your script should accept and automatically generates help messages and error messages. We then use `add_argument()` to add a positional argument named `contract_path`. This argument is required and should be a path to the oracle contract that you want to upload. The help argument provides a description of what this argument does. We further add another positional argument named `contract_address`. This argument is optional (`nargs="?"` allows it to be omitted), and it should be of type `Address`. The `type` argument specifies the type of the argument. In this case, `Address` is a custom type or class used to represent addresses. The `help` argument provides a description of what this argument does. At the end, we parse the command-line arguments provided when the script is executed. It returns an object that contains the values of the parsed arguments. - update_message = { - "update_oracle_value": { - "value": str(value), - "decimals": str(ORACLE_VALUE_DECIMALS), - } - } - contract.execute(update_message, wallet).wait_to_complete() +5. We then need to proceed and define our `main()` function: + + + + + + + + ```py copy filename="aerial_oracle.py" + + def main(): + """Run main.""" + args = _parse_commandline() + + wallet = LocalWallet.generate() + + ledger = LedgerClient(NetworkConfig.fetchai_stable_testnet()) + faucet_api = FaucetApi(NetworkConfig.fetchai_stable_testnet()) + + wallet_balance = ledger.query_bank_balance(wallet.address()) + + while wallet_balance < (10 ** 18): + print("Providing wealth to wallet...") + faucet_api.get_wealth(wallet.address()) + wallet_balance = ledger.query_bank_balance(wallet.address()) + + contract = LedgerContract(args.contract_path, ledger, address=args.contract_address) + + if not args.contract_address: + instantiation_message = {"fee": "100"} + contract.deploy(instantiation_message, wallet, funds="1atestfet") + + print(f"Oracle contract deployed at: {contract.address}") + + grant_role_message = {"grant_oracle_role": {"address": wallet}} + contract.execute(grant_role_message, wallet).wait_to_complete() + + print(f"Oracle role granted to address: {wallet}") + + while True: + resp = requests.get(COIN_PRICE_URL, timeout=DEFAULT_TIMEOUT).json() + price = resp["fetch-ai"]["usd"] + value = int(price * 10 ** ORACLE_VALUE_DECIMALS) + + update_message = { + "update_oracle_value": { + "value": str(value), + "decimals": str(ORACLE_VALUE_DECIMALS), + } + } + contract.execute(update_message, wallet).wait_to_complete() + + print(f"Oracle value updated to: {price} USD") + print(f"Next update in {UPDATE_INTERVAL_SECONDS} seconds...") + sleep(UPDATE_INTERVAL_SECONDS) + + + if __name__ == "__main__": + main() + +``` + + + - print(f"Oracle value updated to: {price} USD") - print(f"Next update in {UPDATE_INTERVAL_SECONDS} seconds...") - sleep(UPDATE_INTERVAL_SECONDS) - if __name__ == "__main__": - main() - ``` This defines our `main()` function. When we run the script, the code inside `main()` will be executed. `args = _parse_commandline()` calls the `_parse_commandline()` function that we defined earlier. It parses the command-line arguments and returns an object (`args`) containing the values of the parsed arguments. We then generate a new local wallet, and then create a client for interacting with a blockchain ledger, using `LedgerClient()` class. We configured it to use the Fetch.ai stable testnet. We then create a client for interacting with a faucet API and query the balance of the wallet's address using the `query_bank_balance()` method. We also define an initial `while` loop which continues as long as the `wallet_balance` is less than `10**18`. Inside this first loop: it prints a message indicating that wealth is being provided to the wallet, then it calls the faucet API to get wealth for the wallet, and it updates the `wallet_balance` by querying the bank balance again. @@ -281,39 +357,76 @@ Now, we will write a script that deploys a contract that can request the oracle 2. We start by importing the needed classes and define a `REQUEST_INTERVAL_SECONDS` variable: - ```py copy - import argparse - from time import sleep + + + + + + + ```py copy filename="aerial_oracle_client.py" + + import argparse + from time import sleep + + from cosmpy.aerial.client import LedgerClient, NetworkConfig + from cosmpy.aerial.contract import LedgerContract + from cosmpy.aerial.faucet import FaucetApi + from cosmpy.aerial.wallet import LocalWallet + from cosmpy.crypto.address import Address + + REQUEST_INTERVAL_SECONDS = 10 + +``` + + + + - from cosmpy.aerial.client import LedgerClient, NetworkConfig - from cosmpy.aerial.contract import LedgerContract - from cosmpy.aerial.faucet import FaucetApi - from cosmpy.aerial.wallet import LocalWallet - from cosmpy.crypto.address import Address - REQUEST_INTERVAL_SECONDS = 10 - ``` 3. Like before, we proceed and define a `_parse_commandline()` function: - ```py copy - def _parse_commandline(): - parser = argparse.ArgumentParser() - parser.add_argument( - "contract_path", help="The path to the oracle client contract to upload" - ) - parser.add_argument( - "oracle_contract_address", - type=Address, - help="The address of the oracle contract", - ) - parser.add_argument( - "contract_address", - nargs="?", - type=Address, - help="The address of the oracle client contract if already deployed", - ) - return parser.parse_args() - ``` + + + + + + + ```py copy filename="aerial_oracle_client.py" + + def _parse_commandline(): + parser = argparse.ArgumentParser() + parser.add_argument( + "contract_path", help="The path to the oracle client contract to upload" + ) + parser.add_argument( + "oracle_contract_address", + type=Address, + help="The address of the oracle contract", + ) + parser.add_argument( + "contract_address", + nargs="?", + type=Address, + help="The address of the oracle client contract if already deployed", + ) + return parser.parse_args() + +``` + + + + + This `_parse_commandline()` function is designed to parse command-line arguments. We first create a `parser` object. This object is used to specify what command-line arguments the program should expect. We then use the `add_argument()` method to define the arguments that the program expects. In this function, there are three arguments being defined: @@ -325,47 +438,65 @@ Now, we will write a script that deploys a contract that can request the oracle 4. We can now define our `main()` function. - ```py copy - def main(): - """Run main.""" - args = _parse_commandline() - - wallet = LocalWallet.generate() - - ledger = LedgerClient(NetworkConfig.fetchai_stable_testnet()) - faucet_api = FaucetApi(NetworkConfig.fetchai_stable_testnet()) - - wallet_balance = ledger.query_bank_balance(wallet.address()) - - while wallet_balance < (10**18): - print("Providing wealth to wallet...") - faucet_api.get_wealth(wallet.address()) - wallet_balance = ledger.query_bank_balance(wallet.address()) - - contract = LedgerContract(args.contract_path, ledger, address=args.contract_address) + + + + - if not args.contract_address: - instantiation_message = { - "oracle_contract_address": str(args.oracle_contract_address) - } - contract.deploy(instantiation_message, wallet) + + ```py copy filename="aerial_oracle_client.py" - print(f"Oracle client contract deployed at: {contract.address}") + def main(): + """Run main.""" + args = _parse_commandline() + + wallet = LocalWallet.generate() + + ledger = LedgerClient(NetworkConfig.fetchai_stable_testnet()) + faucet_api = FaucetApi(NetworkConfig.fetchai_stable_testnet()) + + wallet_balance = ledger.query_bank_balance(wallet.address()) + + while wallet_balance < (10**18): + print("Providing wealth to wallet...") + faucet_api.get_wealth(wallet.address()) + wallet_balance = ledger.query_bank_balance(wallet.address()) + + contract = LedgerContract(args.contract_path, ledger, address=args.contract_address) + + if not args.contract_address: + instantiation_message = { + "oracle_contract_address": str(args.oracle_contract_address) + } + contract.deploy(instantiation_message, wallet) + + print(f"Oracle client contract deployed at: {contract.address}") + + while True: + request_message = {"query_oracle_value": {}} + contract.execute( + request_message, wallet, funds="100atestfet" + ).wait_to_complete() + + result = contract.query({"oracle_value": {}}) + print(f"Oracle value successfully retrieved: {result}") + + sleep(REQUEST_INTERVAL_SECONDS) + + if __name__ == "__main__": + main() - while True: - request_message = {"query_oracle_value": {}} - contract.execute( - request_message, wallet, funds="100atestfet" - ).wait_to_complete() +``` + - result = contract.query({"oracle_value": {}}) - print(f"Oracle value successfully retrieved: {result}") + - sleep(REQUEST_INTERVAL_SECONDS) - if __name__ == "__main__": - main() - ``` The first line calls the `_parse_commandline()` function that we defined earlier. It will parse the command-line arguments and return an object (`args`) containing the parsed values. We proceed and generate a new local wallet, `wallet`, and then create a new `ledger` object for interacting with the blockchain or ledger system, using `LedgerClient()`. Afterwards, we create a `FaucetApi` object, `faucet_api`, which is used for interacting with the faucet service. We use the `query_bank_balance()` method to query the balance associated with the wallet's address. We then define a `while` loop which will continue as long as the `wallet_balance` is less than `10**18`. This is to ensure the wallet has a sufficient balance. Afterwards, we use the `get_wealth()` method to add wealth to the wallet, and then create a new `LedgerContract()` object which takes the `contract_path`, the `ledger` object, and an optional `contract_address`. `if not args.contract_address:` checks if `args.contract_address` is not provided. If it has not been provided, it means that the contract has not been deployed yet. We then create an `instantiation_message`, which contains the data needed for deploying the contract. `contract.deploy()` deploys the contract with the provided `instantiation_message` and the `wallet`. The code then prints out the address of the deployed contract. Finally, we define a second loop starting with `while True:` which repeatedly executes the following steps: @@ -379,75 +510,93 @@ Now, we will write a script that deploys a contract that can request the oracle The overall script should be as follows: -```py copy filename="aerial_oracle_client.py" -import argparse -from time import sleep - -from cosmpy.aerial.client import LedgerClient, NetworkConfig -from cosmpy.aerial.contract import LedgerContract -from cosmpy.aerial.faucet import FaucetApi -from cosmpy.aerial.wallet import LocalWallet -from cosmpy.crypto.address import Address - -REQUEST_INTERVAL_SECONDS = 10 - -def _parse_commandline(): - parser = argparse.ArgumentParser() - parser.add_argument( - "contract_path", help="The path to the oracle client contract to upload" - ) - parser.add_argument( - "oracle_contract_address", - type=Address, - help="The address of the oracle contract", - ) - parser.add_argument( - "contract_address", - nargs="?", - type=Address, - help="The address of the oracle client contract if already deployed", - ) - return parser.parse_args() - -def main(): - """Run main.""" - args = _parse_commandline() - - wallet = LocalWallet.generate() - - ledger = LedgerClient(NetworkConfig.fetchai_stable_testnet()) - faucet_api = FaucetApi(NetworkConfig.fetchai_stable_testnet()) - - wallet_balance = ledger.query_bank_balance(wallet.address()) - - while wallet_balance < (10**18): - print("Providing wealth to wallet...") - faucet_api.get_wealth(wallet.address()) - wallet_balance = ledger.query_bank_balance(wallet.address()) - - contract = LedgerContract(args.contract_path, ledger, address=args.contract_address) - - if not args.contract_address: - instantiation_message = { - "oracle_contract_address": str(args.oracle_contract_address) - } - contract.deploy(instantiation_message, wallet) - - print(f"Oracle client contract deployed at: {contract.address}") - - while True: - request_message = {"query_oracle_value": {}} - contract.execute( - request_message, wallet, funds="100atestfet" - ).wait_to_complete() - - result = contract.query({"oracle_value": {}}) - print(f"Oracle value successfully retrieved: {result}") - - sleep(REQUEST_INTERVAL_SECONDS) - -if __name__ == "__main__": - main() + + + + + + + ```py copy filename="aerial_oracle_client.py" + + import argparse + from time import sleep + + from cosmpy.aerial.client import LedgerClient, NetworkConfig + from cosmpy.aerial.contract import LedgerContract + from cosmpy.aerial.faucet import FaucetApi + from cosmpy.aerial.wallet import LocalWallet + from cosmpy.crypto.address import Address + + REQUEST_INTERVAL_SECONDS = 10 + + def _parse_commandline(): + parser = argparse.ArgumentParser() + parser.add_argument( + "contract_path", help="The path to the oracle client contract to upload" + ) + parser.add_argument( + "oracle_contract_address", + type=Address, + help="The address of the oracle contract", + ) + parser.add_argument( + "contract_address", + nargs="?", + type=Address, + help="The address of the oracle client contract if already deployed", + ) + return parser.parse_args() + + def main(): + """Run main.""" + args = _parse_commandline() + + wallet = LocalWallet.generate() + + ledger = LedgerClient(NetworkConfig.fetchai_stable_testnet()) + faucet_api = FaucetApi(NetworkConfig.fetchai_stable_testnet()) + + wallet_balance = ledger.query_bank_balance(wallet.address()) + + while wallet_balance < (10**18): + print("Providing wealth to wallet...") + faucet_api.get_wealth(wallet.address()) + wallet_balance = ledger.query_bank_balance(wallet.address()) + + contract = LedgerContract(args.contract_path, ledger, address=args.contract_address) + + if not args.contract_address: + instantiation_message = { + "oracle_contract_address": str(args.oracle_contract_address) + } + contract.deploy(instantiation_message, wallet) + + print(f"Oracle client contract deployed at: {contract.address}") + + while True: + request_message = {"query_oracle_value": {}} + contract.execute( + request_message, wallet, funds="100atestfet" + ).wait_to_complete() + + result = contract.query({"oracle_value": {}}) + print(f"Oracle value successfully retrieved: {result}") + + sleep(REQUEST_INTERVAL_SECONDS) + + if __name__ == "__main__": + main() + ``` + + + + + Bear in mind that specific data related to the oracle's address and contract need to be provided by hand based on your personalized information! diff --git a/pages/guides/fetch-network/cosmpy/use-cases/stake-auto-compounder.mdx b/pages/guides/fetch-network/cosmpy/use-cases/stake-auto-compounder.mdx index f10541ff..a66754ae 100644 --- a/pages/guides/fetch-network/cosmpy/use-cases/stake-auto-compounder.mdx +++ b/pages/guides/fetch-network/cosmpy/use-cases/stake-auto-compounder.mdx @@ -1,4 +1,4 @@ -import { CodeGroup, CodeSegment, DocsCode, GithubCodeSegment } from "../../../../components/code"; +import { CodeGroup, CodeSegment, DocsCode, GithubCodeSegment } from "../../../../../components/code"; # Stake auto-compounder @@ -374,3 +374,4 @@ The overall script should look as follows: + diff --git a/pages/guides/fetch-network/cosmpy/use-cases/stake-optimizer.mdx b/pages/guides/fetch-network/cosmpy/use-cases/stake-optimizer.mdx index e4808f13..ed8e8f6c 100644 --- a/pages/guides/fetch-network/cosmpy/use-cases/stake-optimizer.mdx +++ b/pages/guides/fetch-network/cosmpy/use-cases/stake-optimizer.mdx @@ -1,4 +1,4 @@ -import { CodeGroup, CodeSegment, DocsCode, GithubCodeSegment } from "../../../../components/code"; +import { CodeGroup, CodeSegment, DocsCode, GithubCodeSegment } from "../../../../../components/code"; # Stake optimizer @@ -485,3 +485,4 @@ Now that we have presented the concepts and ideas behind the stake optimizer, ha + diff --git a/pages/guides/fetch-network/cosmpy/use-cases/swap_automation.mdx b/pages/guides/fetch-network/cosmpy/use-cases/swap_automation.mdx index 81dee076..2481c527 100644 --- a/pages/guides/fetch-network/cosmpy/use-cases/swap_automation.mdx +++ b/pages/guides/fetch-network/cosmpy/use-cases/swap_automation.mdx @@ -1,4 +1,4 @@ -import { CodeGroup, CodeSegment, DocsCode, GithubCodeSegment } from "../../../../components/code"; +import { CodeGroup, CodeSegment, DocsCode, GithubCodeSegment } from "../../../../../components/code"; # Swap automation 🔄 diff --git a/pages/guides/fetch-network/cosmpy/use-cases/wallet-top-up.mdx b/pages/guides/fetch-network/cosmpy/use-cases/wallet-top-up.mdx index 55e06e8d..b73b105e 100644 --- a/pages/guides/fetch-network/cosmpy/use-cases/wallet-top-up.mdx +++ b/pages/guides/fetch-network/cosmpy/use-cases/wallet-top-up.mdx @@ -1,4 +1,4 @@ -import { CodeGroup, CodeSegment, DocsCode, GithubCodeSegment } from "../../../../components/code"; +import { CodeGroup, CodeSegment, DocsCode, GithubCodeSegment } from "../../../../../components/code"; # Wallet top-up 💵 @@ -550,3 +550,4 @@ The overall script should be as follows: + diff --git a/pages/guides/quickstart-with/CrewAI/creating-an-agent-with-crewai.mdx b/pages/guides/quickstart-with/CrewAI/creating-an-agent-with-crewai.mdx index 72ed44a3..5637867d 100644 --- a/pages/guides/quickstart-with/CrewAI/creating-an-agent-with-crewai.mdx +++ b/pages/guides/quickstart-with/CrewAI/creating-an-agent-with-crewai.mdx @@ -395,121 +395,144 @@ The `senior_research_analyst_agent`, is designed to handle requests for city-spe When a request is received with a city name, the agent logs the request, conducts a comprehensive analysis, and returns a report that combines AI insights with real-time weather data. This functionality makes it a valuable tool for research organizations and tech consultancies seeking relevant information. - ```python copy filename="crewai_agent_1.py" - from uagents import Agent, Context, Model - import os - from crewai import Agent as CrewAIAgent, Task, Crew, Process - from crewai_tools import SerperDevTool - - senior_research_analyst_agent = Agent( - name="senior_research_analyst_agent", - seed="senior_research_analyst_agent_seed", - port=8001, - endpoint=["http://127.0.0.1:8001/submit"], - ) - - class CityRequestModel(Model): - city: str - - class ResearchReportModel(Model): - report: str - - os.environ["OPENAI_API_KEY"] = "" - os.environ["SERPER_API_KEY"] = "" - - class SeniorResearchAnalyst: - def __init__(self): - """ - Initializes the Senior Research Analyst agent with a search tool. - """ - self.search_tool = SerperDevTool() - - self.researcher = CrewAIAgent( - role="Senior Research Analyst", - goal="Uncover cutting-edge developments in AI and provide weather updates.", - backstory="""You work at a leading tech think tank. - Your expertise lies in identifying emerging trends and understanding external factors like weather.""", - verbose=True, - allow_delegation=False, - tools=[self.search_tool], - ) - - def create_task(self, city: str) -> Task: - """ - Creates a task for conducting research on AI advancements and retrieving weather updates. - - Parameters: - - city: str, the city for which the weather update is requested. - - Returns: - - Task: The created task with the specified description and expected output. - """ - task_description = ( - f"Conduct a comprehensive analysis of the latest advancements in AI in 2024. " - f"Also, use the search tool to provide the current weather update for {city}." - ) - - return Task( - description=task_description, - expected_output="Full analysis report with weather data", - agent=self.researcher, - ) - - def run_process(self, city: str): - """ - Runs the process for the created task and retrieves the result. - - Parameters: - - city: str, the city for which the task is run. - - Returns: - - result: The output from the CrewAI process after executing the task. - """ - task = self.create_task(city) - crew = Crew( - agents=[self.researcher], - tasks=[task], - verbose=True, - process=Process.sequential, - ) - result = crew.kickoff() - return result - - @senior_research_analyst_agent.on_message(model=CityRequestModel, replies=ResearchReportModel) - async def handle_city_request(ctx: Context, sender: str, msg: CityRequestModel): - """ - Handles incoming messages requesting city information. - - What it does: - - Logs the received city name. - - Runs the research process for the specified city and sends the report back to the sender. - - Parameters: - - ctx: Context, provides the execution context for logging and messaging. - - sender: str, the address of the sender agent. - - msg: CityRequestModel, the received message containing the city name. - - Returns: - - None: Sends the research report to the sender agent. - """ - ctx.logger.info(f"Received message from {sender} with city: {msg.city}") - research_analyst = SeniorResearchAnalyst() - gather_task_result = research_analyst.run_process(msg.city) - await ctx.send(sender, ResearchReportModel(report=str(gather_task_result))) - - if __name__ == "__main__": - """ - Starts the communication agent and begins listening for messages. - - What it does: - - Runs the agent, enabling it to send/receive messages and handle events. - - Returns: - - None: Runs the agent loop indefinitely. - """ - senior_research_analyst_agent.run() + + + + + + + ```py copy filename="crewai_agent_1.py" + + from uagents import Agent, Context, Model + import os + from crewai import Agent as CrewAIAgent, Task, Crew, Process + from crewai_tools import SerperDevTool + + senior_research_analyst_agent = Agent( + name="senior_research_analyst_agent", + seed="senior_research_analyst_agent_seed", + port=8001, + endpoint=["http://127.0.0.1:8001/submit"], + ) + + + class CityRequestModel(Model): + city: str + + + class ResearchReportModel(Model): + report: str + + + os.environ["OPENAI_API_KEY"] = "" + os.environ["SERPER_API_KEY"] = "" + + + class SeniorResearchAnalyst: + def __init__(self): + """ + Initializes the Senior Research Analyst agent with a search tool. + """ + self.search_tool = SerperDevTool() + + self.researcher = CrewAIAgent( + role="Senior Research Analyst", + goal="Uncover cutting-edge developments in AI and provide weather updates.", + backstory="""You work at a leading tech think tank. + Your expertise lies in identifying emerging trends and understanding external factors like weather.""", + verbose=True, + allow_delegation=False, + tools=[self.search_tool], + ) + + def create_task(self, city: str) -> Task: + """ + Creates a task for conducting research on AI advancements and retrieving weather updates. + + Parameters: + - city: str, the city for which the weather update is requested. + + Returns: + - Task: The created task with the specified description and expected output. + """ + task_description = ( + f"Conduct a comprehensive analysis of the latest advancements in AI in 2024. " + f"Also, use the search tool to provide the current weather update for {city}." + ) + + return Task( + description=task_description, + expected_output="Full analysis report with weather data", + agent=self.researcher, + ) + + def run_process(self, city: str): + """ + Runs the process for the created task and retrieves the result. + + Parameters: + - city: str, the city for which the task is run. + + Returns: + - result: The output from the CrewAI process after executing the task. + """ + task = self.create_task(city) + crew = Crew( + agents=[self.researcher], + tasks=[task], + verbose=True, + process=Process.sequential, + ) + result = crew.kickoff() + return result + + + @senior_research_analyst_agent.on_message(model=CityRequestModel, replies=ResearchReportModel) + async def handle_city_request(ctx: Context, sender: str, msg: CityRequestModel): + """ + Handles incoming messages requesting city information. + + What it does: + - Logs the received city name. + - Runs the research process for the specified city and sends the report back to the sender. + + Parameters: + - ctx: Context, provides the execution context for logging and messaging. + - sender: str, the address of the sender agent. + - msg: CityRequestModel, the received message containing the city name. + + Returns: + - None: Sends the research report to the sender agent. + """ + ctx.logger.info(f"Received message from {sender} with city: {msg.city}") + research_analyst = SeniorResearchAnalyst() + gather_task_result = research_analyst.run_process(msg.city) + await ctx.send(sender, ResearchReportModel(report=str(gather_task_result))) + + + if __name__ == "__main__": + """ + Starts the communication agent and begins listening for messages. + + What it does: + - Runs the agent, enabling it to send/receive messages and handle events. + + Returns: + - None: Runs the agent loop indefinitely. + """ + senior_research_analyst_agent.run() + +``` + + + + - ``` ### Agent two: Research Asking Agent @@ -523,79 +546,102 @@ The `research_asking_agent` agent is designed to initiate requests for city-spec This agent operates continuously, enabling effective communication and retrieval of city-related research insights. - ```python copy filename="crewai_agent_2.py" - from uagents import Agent, Context, Model - - class CityRequestModel(Model): - city: str - - class ResearchReportModel(Model): - report: str - - research_asking_agent = Agent( - name="research_asking_agent", - seed="research_asking_agent_seed", - port=8000, - endpoint=["http://127.0.0.1:8000/submit"], - ) - - TARGET_AGENT_ADDRESS = ( - "agent1qgxfhzy78m2qfdsg726gtj4vnd0hkqx96xwprng2e4rmn0xfq7p35u6dz8q" - ) - DEFAULT_CITY = "London" - - @research_asking_agent.on_event("startup") - async def on_startup(ctx: Context): - """ - Triggered when the agent starts up. - - What it does: - - Logs the agent's name and address. - - Sends a message to the target agent with the default city (e.g., 'London'). - - Parameters: - - ctx: Context, provides the execution context for logging and messaging. - - Returns: - - None: Sends the message to the target agent asynchronously. - """ - ctx.logger.info( - f"Hello, I'm {research_asking_agent.name}, and my address is {research_asking_agent.address}." - ) - - await ctx.send(TARGET_AGENT_ADDRESS, CityRequestModel(city=DEFAULT_CITY)) - - @research_asking_agent.on_message(model=ResearchReportModel) - async def handle_research_report(ctx: Context, sender: str, msg: ResearchReportModel): - """ - Triggered when a message of type ResearchReportModel is received. - - What it does: - - Logs the sender's address and the research report received. + + + + - Parameters: - - ctx: Context, provides the execution context for logging and messaging. - - sender: str, the address of the sender agent. - - msg: ResearchReportModel, the received research report. + + ```py copy filename="crewai_agent_2.py" - Returns: - - None: Processes the message and logs it. - """ - ctx.logger.info(f"Received research report from {sender}: {msg.report}") + from uagents import Agent, Context, Model + + + class CityRequestModel(Model): + city: str + + + class ResearchReportModel(Model): + report: str + + + research_asking_agent = Agent( + name="research_asking_agent", + seed="research_asking_agent_seed", + port=8000, + endpoint=["http://127.0.0.1:8000/submit"], + ) + + TARGET_AGENT_ADDRESS = ( + "agent1qgxfhzy78m2qfdsg726gtj4vnd0hkqx96xwprng2e4rmn0xfq7p35u6dz8q" + ) + DEFAULT_CITY = "London" + + + @research_asking_agent.on_event("startup") + async def on_startup(ctx: Context): + """ + Triggered when the agent starts up. + + What it does: + - Logs the agent's name and address. + - Sends a message to the target agent with the default city (e.g., 'London'). + + Parameters: + - ctx: Context, provides the execution context for logging and messaging. + + Returns: + - None: Sends the message to the target agent asynchronously. + """ + ctx.logger.info( + f"Hello, I'm {research_asking_agent.name}, and my address is {research_asking_agent.address}." + ) + + await ctx.send(TARGET_AGENT_ADDRESS, CityRequestModel(city=DEFAULT_CITY)) + + + @research_asking_agent.on_message(model=ResearchReportModel) + async def handle_research_report(ctx: Context, sender: str, msg: ResearchReportModel): + """ + Triggered when a message of type ResearchReportModel is received. + + What it does: + - Logs the sender's address and the research report received. + + Parameters: + - ctx: Context, provides the execution context for logging and messaging. + - sender: str, the address of the sender agent. + - msg: ResearchReportModel, the received research report. + + Returns: + - None: Processes the message and logs it. + """ + ctx.logger.info(f"Received research report from {sender}: {msg.report}") + + + if __name__ == "__main__": + """ + Starts the research analyst agent and begins listening for events. + + What it does: + - Runs the agent, enabling it to send/receive messages and handle events. + + Returns: + - None: Runs the agent loop indefinitely. + """ + research_asking_agent.run() - if __name__ == "__main__": - """ - Starts the research analyst agent and begins listening for events. +``` + - What it does: - - Runs the agent, enabling it to send/receive messages and handle events. + - Returns: - - None: Runs the agent loop indefinitely. - """ - research_asking_agent.run() - ``` ### Output