### Open-AEA Echo Skill Demo Setup and Run Source: https://open-aea.docs.autonolas.tech/quickstart A step-by-step guide to fetching, installing dependencies, generating keys, and running a pre-existing Open-AEA echo skill. Also includes how to interact with the running AEA by sending a message. ```Shell aea fetch open_aea/my_first_aea:0.1.0:bafybeiakpjbpsqbmgqdg6c36nhujqmk446u2qn7jvi2lefmnyxtmnv3tqe --remote cd my_first_aea ``` ```Shell aea install ``` ```Shell aea generate-key ethereum aea add-key ethereum ``` ```Shell aea run ``` ```Shell echo 'my_first_aea,sender_aea,fetchai/default:1.0.0,\x12\x10\x08\x01\x12\x011*\t*\x07\n\x05hello,' >> input_file ``` -------------------------------- ### Fetch and Install Gym AEA Source: https://open-aea.docs.autonolas.tech/gym-skill This command fetches a specific version of the 'gym_aea' project from a remote source, navigates into its directory, and installs its dependencies. This is the recommended way to get started with the gym AEA. ```shell aea fetch open_aea/gym_aea:0.1.0:bafybeifb6ldx7mvgqo7c6blusile4rvneiw3uxjvy2vxcgn7v4pw3la5xu --remote cd gym_aea aea install ``` -------------------------------- ### Install AEA Project Dependencies Source: https://open-aea.docs.autonolas.tech/http-connection-and-skill This command installs all necessary dependencies for the AEA project, ensuring that all required packages and libraries are available for the agent to function correctly. ```bash aea install ``` -------------------------------- ### Install AEA Framework from PyPI Source: https://open-aea.docs.autonolas.tech/raspberry-set-up This command installs the complete Autonomous Economic Agent (AEA) framework, including all its optional dependencies, directly from the Python Package Index (PyPI). This is the final step to get the AEA software ready for use. ```bash pip install aea[all] ``` -------------------------------- ### Automated Open-AEA Installation on MacOS and Ubuntu Source: https://open-aea.docs.autonolas.tech/quickstart Commands to download and execute the automated installation script for Open-AEA dependencies and the framework itself on MacOS and Ubuntu systems, simplifying the setup process. ```Shell curl https://raw.githubusercontent.com/valory-xyz/open-aea/main/scripts/install.sh --output install.sh chmod +x install.sh ./install.sh ``` -------------------------------- ### Set up and Run AEA HTTP Echo Server Source: https://open-aea.docs.autonolas.tech/http-echo-demo Commands to initialize, configure, and run the open-aea http_echo agent. This sequence fetches the pre-built skill, sets up necessary keys, installs dependencies, and starts the AEA, making it available as an HTTP server on port 5000. ```bash pipenv shell aea fetch open_aea/http_echo:0.1.0:bafybeic2zpk3epl4mnkrufl22u5wtiohitgab5otcjruhpqiicsijp3jem --remote cd http_echo aea generate-key ethereum; aea add-key ethereum aea install aea run --aev Adding protocol 'open_aea/signing:1.0.0'... Successfully added protocol 'open_aea/signing:1.0.0'. Adding protocol 'valory/http:1.0.0'... Successfully added protocol 'valory/http:1.0.0'. Adding protocol 'fetchai/default:1.0.0'... Successfully added protocol 'fetchai/default:1.0.0'. Adding connection 'valory/http_server:0.22.0'... Successfully added connection 'valory/http_server:0.22.0'. Adding skill 'fetchai/http_echo:0.20.0'... Successfully added skill 'fetchai/http_echo:0.20.0'. Agent http_echo successfully fetched. _ _____ _ / \ | ____| / \ / _ \ | _| / _ \ / ___ \ | |___ / ___ \ /_/ \_\|_____|/_/ \_\ v1.4.0 Starting AEA 'http_echo' in 'async' mode... info: [http_echo] HTTP Server has connected to port: 5000. info: [http_echo] Start processing messages... ``` -------------------------------- ### Complete FetchAI Transaction Example with AEA Wallet Setup Source: https://open-aea.docs.autonolas.tech/standalone-transaction This full example demonstrates setting up two FetchAI wallets, generating testnet wealth for 'wallet_1', and then executing a transfer transaction to 'wallet_2'. It covers private key creation, wallet initialization, wealth generation, and the entire transaction flow using 'LedgerApis'. ```python import logging from aea_ledger_fetchai import FetchAICrypto from aea.crypto.helpers import create_private_key, try_generate_testnet_wealth from aea.crypto.ledger_apis import LedgerApis from aea.crypto.wallet import Wallet logger = logging.getLogger("aea") logging.basicConfig(level=logging.INFO) FETCHAI_PRIVATE_KEY_FILE_1 = "fetchai_private_key_1.txt" FETCHAI_PRIVATE_KEY_FILE_2 = "fetchai_private_key_2.txt" def run(): """Run demo.""" # Create a private keys create_private_key( FetchAICrypto.identifier, private_key_file=FETCHAI_PRIVATE_KEY_FILE_1 ) create_private_key( FetchAICrypto.identifier, private_key_file=FETCHAI_PRIVATE_KEY_FILE_2 ) # Set up the wallets wallet_1 = Wallet({FetchAICrypto.identifier: FETCHAI_PRIVATE_KEY_FILE_1}) wallet_2 = Wallet({FetchAICrypto.identifier: FETCHAI_PRIVATE_KEY_FILE_2}) # Generate some wealth try_generate_testnet_wealth( FetchAICrypto.identifier, wallet_1.addresses[FetchAICrypto.identifier] ) logger.info( "Sending amount to {}".format(wallet_2.addresses.get(FetchAICrypto.identifier)) ) # Create the transaction and send it to the ledger. tx_nonce = LedgerApis.generate_tx_nonce( FetchAICrypto.identifier, wallet_2.addresses.get(FetchAICrypto.identifier), wallet_1.addresses.get(FetchAICrypto.identifier), ) transaction = LedgerApis.get_transfer_transaction( identifier=FetchAICrypto.identifier, sender_address=wallet_1.addresses.get(FetchAICrypto.identifier), destination_address=wallet_2.addresses.get(FetchAICrypto.identifier), amount=1, tx_fee=1, tx_nonce=tx_nonce, ) signed_transaction = wallet_1.sign_transaction( FetchAICrypto.identifier, transaction ) transaction_digest = LedgerApis.send_signed_transaction( FetchAICrypto.identifier, signed_transaction ) logger.info("Transaction complete.") logger.info("The transaction digest is {}".format(transaction_digest)) if __name__ == "__main__": run() ``` -------------------------------- ### Install AEA Packages for Multiplexer Example Source: https://open-aea.docs.autonolas.tech/multiplexer-standalone This snippet demonstrates how to prepare the environment by creating a temporary AEA project, adding required protocols and connections (default and stub) from remote sources, and then pushing them locally. This ensures all necessary dependencies are available for the Multiplexer example. ```bash mkdir packages aea create my_aea cd my_aea aea add protocol fetchai/default:1.0.0:bafybeiaf3qhrdttthrisrl2tlpt3mpo5btkozw2dnxlj4cbqq56ilcl6oa --remote aea push connection fetchai/default --local aea add connection fetchai/stub:0.21.0:bafybeibqrgcch7dufgvzoxi43vxbbhx6isfn3njhq5q3eud6yhhyjdnthm --remote aea push connection fetchai/stub --local cd .. aea delete my_aea ``` -------------------------------- ### AEA Class Method: setup Source: https://open-aea.docs.autonolas.tech/api/aea Initializes the agent by invoking the `setup()` method on its associated resources. ```APIDOC def setup() -> None # Set up the agent. # Calls setup() on the resources. ``` -------------------------------- ### Start and Stop AEA Agent Wrapper (Python) Source: https://open-aea.docs.autonolas.tech/performance-benchmark This snippet shows the basic pattern for starting and stopping an AEA agent wrapper. The `start()` method initializes the agent's loop, and `stop()` gracefully shuts it down. ```Python aea_test_wrapper.start() ... aea_test_wrapper.stop() ``` -------------------------------- ### Install Python Development Headers on Ubuntu/Debian Source: https://open-aea.docs.autonolas.tech/quickstart Command to install Python development headers, which are required for compiling Python extensions, specifically for Ubuntu/Debian systems. The example is for Python 3.10. ```Shell sudo apt-get install python3.10-dev ``` -------------------------------- ### Implement SkillComponent Setup Source: https://open-aea.docs.autonolas.tech/api/skills/base Abstract method that must be implemented by subclasses to define the component's setup logic, executed when the skill is loaded. ```Python @abstractmethod def setup() -> None ``` -------------------------------- ### Setup Function (Python API) Source: https://open-aea.docs.autonolas.tech/api/protocols/dialogue/base Executes initial setup procedures for the component or system. This function is typically invoked once at the beginning of the component's lifecycle. ```python def setup() -> None ``` ```APIDOC Function: setup Purpose: Set up. Arguments: None Returns: None ``` -------------------------------- ### Setting up Test Environment with BaseSkillTestCase Source: https://open-aea.docs.autonolas.tech/skill-testing Illustrates the use of the `setup()` class method to initialize the test environment before each test. It shows how to call the superclass's `setup()` and access skill components like behaviours for testing. ```Python @classmethod def setup(cls): """Setup the test class.""" super().setup() cls.my_behaviour = cast( MyBehaviour, cls._skill.skill_context.behaviours.my_behaviour ) ``` -------------------------------- ### Start Benchmark Measurement (Python) Source: https://open-aea.docs.autonolas.tech/performance-benchmark This call to `benchmark.start()` signals the beginning of the measured section of the code. All code executed after this point will be included in the performance metrics. ```Python benchmark.start() ``` -------------------------------- ### Install Project Dependencies and Build Components Source: https://open-aea.docs.autonolas.tech/api/manager/utils Installs all necessary project dependencies and builds any required components for the given project. This ensures the project is ready for execution. ```Python def project_install_and_build(project: Project) -> None ``` -------------------------------- ### Run AEA Agent Source: https://open-aea.docs.autonolas.tech/http-connection-and-skill This command starts the Autonomous Economic Agent (AEA), bringing it online and enabling it to process configured connections and skills. It must be run in a terminal after configuration. ```bash aea run ``` -------------------------------- ### Install AEA Dependencies Source: https://open-aea.docs.autonolas.tech/cli-commands Installs the necessary dependencies for the AEA project. The `-r` flag can be used to specify a requirements file, and `--install-deps` installs general dependencies. ```CLI install [-r ] ``` -------------------------------- ### APIDOC: Run Install Subprocess Source: https://open-aea.docs.autonolas.tech/api/helpers/install_dependency Executes an installation command as a subprocess. Returns the return code of the subprocess, with an optional timeout. ```APIDOC def run_install_subprocess(install_command: List[str], install_timeout: float = 300) -> int Arguments: install_command: list strings of the command install_timeout: timeout to wait pip to install Returns: the return code of the subprocess ``` -------------------------------- ### Python: Context Manager for Package Installation Source: https://open-aea.docs.autonolas.tech/api/plugins/aea_cli_benchmark/utils A Python context manager designed to download and install specified packages. It ensures that packages are properly set up for the duration of a block of code, with an optional parameter to specify the installation directory. ```Python @contextmanager def with_packages(packages: List[Tuple[str, str]], packages_dir: Optional[Path] = None) ``` -------------------------------- ### Install Fetch.ai Ledger Plugin Source: https://open-aea.docs.autonolas.tech/standalone-transaction This command installs the `open-aea-ledger-fetchai` plugin, which is essential for interacting with the Fetch.ai ledger within your Python environment. ```bash pip install open-aea-ledger-fetchai ``` -------------------------------- ### Agent setup Method Source: https://open-aea.docs.autonolas.tech/api/agent Sets up the agent. ```APIDOC setup() -> None ``` -------------------------------- ### Install Full AEA Package Source: https://open-aea.docs.autonolas.tech/cli-how-to Instructions to install the complete AEA package, including all dependencies and the CLI, using pip. Provides commands for both bash and zsh shells to ensure proper installation across different environments. ```bash pip install aea[all] ``` ```zsh pip install 'aea[all]' ``` -------------------------------- ### API: Setup Resources Source: https://open-aea.docs.autonolas.tech/api/registries/resources Initializes and sets up all managed resources. This function calls the `setup` method on all registered resources. ```Python def setup() -> None ``` -------------------------------- ### Set Up Dialogue Storage Source: https://open-aea.docs.autonolas.tech/api/protocols/dialogue/base Performs initial setup operations for the dialogue storage. ```APIDOC def setup() -> None ``` -------------------------------- ### APIDOC: Install Multiple Python Dependencies Source: https://open-aea.docs.autonolas.tech/api/helpers/install_dependency Installs a list of Python dependencies into the current environment. Requires a list of dependency specifications, a logger, and an optional installation timeout. ```APIDOC def install_dependencies(dependencies: List[Dependency], logger: Logger, install_timeout: float = 300) -> None Arguments: dependencies: dict of dependency name and specification logger: the logger install_timeout: timeout to wait pip to install ``` -------------------------------- ### Install Ethereum Ledger Plugin Source: https://open-aea.docs.autonolas.tech/wealth Installs the `open-aea-ledger-ethereum` plugin, which is required to interact with the Ethereum test-net for AEA agents. ```bash pip install open-aea-ledger-ethereum ``` -------------------------------- ### Install Gym Skill Dependencies Source: https://open-aea.docs.autonolas.tech/gym-skill This command installs all necessary Python package dependencies for the currently added skills, including the 'gym' package, from PyPI. This step is crucial for the skill to function correctly. ```shell aea install ``` -------------------------------- ### Interact with AEA HTTP Server via Python Requests Source: https://open-aea.docs.autonolas.tech/http-connection-and-skill This Python code demonstrates how to send HTTP GET and POST requests to the AEA's running HTTP server. It illustrates expected responses, including a 404 for an undefined path and a 200 for a valid path like `/pets`, showing the returned content. ```python import requests response = requests.get('http://127.0.0.1:8000') response.status_code # >>> 404 # we receive a not found since the path is not available in the api spec response = requests.get('http://127.0.0.1:8000/pets') response.status_code # >>> 200 response.content # >>> b'{"tom": {"type": "cat", "age": 10}}' response = requests.post('http://127.0.0.1:8000/pets') response.status_code # >>> 200 response.content # >>> b'' ``` -------------------------------- ### Install GCC Compiler Source: https://open-aea.docs.autonolas.tech/quickstart Provides commands to install the GCC compiler, a necessary prerequisite for the Open-AEA framework, across different operating systems including Ubuntu, Windows, and MacOS. ```Shell apt-get install gcc ``` ```Shell choco install mingw ``` ```Shell brew install gcc ``` -------------------------------- ### Install Pipenv on Raspberry Pi Source: https://open-aea.docs.autonolas.tech/raspberry-set-up This command installs Pipenv, a Python dependency management tool that simplifies virtual environment creation and package management. It is a prerequisite for installing the AEA framework. ```bash sudo apt-get install pipenv ``` -------------------------------- ### AEA General Documentation and Demo Guides Source: https://open-aea.docs.autonolas.tech/demos This section covers general documentation resources for AEA, including registries for IPFS and package lists, a comprehensive glossary, frequently asked questions (FAQ), and an overview of available demo guides illustrating various multi-agent use-cases. ```APIDOC AEA Registries: - IPFS: ../ipfs_registry/ - Package list: ../package_list/ General Documentation: - Glossary: ../glossary/ - FAQ: ../faq/ Demo Guides: We provide demo guides for multiple use-cases, each one involving several AEAs interacting in a different scenario. ``` -------------------------------- ### APIDOC: TestHandler.setup Method Source: https://open-aea.docs.autonolas.tech/api/plugins/aea_cli_benchmark/case_multiagent/case A no-operation setup method for the TestHandler class. It performs no specific initialization tasks. ```APIDOC def setup() -> None ``` -------------------------------- ### APIDOC: Install Single Python Dependency Source: https://open-aea.docs.autonolas.tech/api/helpers/install_dependency Installs a single Python dependency into the current environment. Specifies the package name, dependency details, and a logger, with an optional installation timeout. ```APIDOC def install_dependency(dependency_name: str, dependency: Dependency, logger: Logger, install_timeout: float = 300) -> None Arguments: dependency_name: name of the python package dependency: Dependency specification logger: the logger install_timeout: timeout to wait pip to install ``` -------------------------------- ### Install AEA project dependencies Source: https://open-aea.docs.autonolas.tech/echo_demo Installs all necessary dependencies for the AEA project, ensuring the agent has all required packages to run correctly. ```shell aea install ``` -------------------------------- ### Execute AEA CLI Install Command Source: https://open-aea.docs.autonolas.tech/api/test_tools/test_cases Executes the AEA CLI install command from the agent's directory. ```Python @classmethod def run_install(cls) -> Result ``` ```APIDOC Returns: Result ``` -------------------------------- ### Python: Example setup.py for AEA Ledger Plugin Source: https://open-aea.docs.autonolas.tech/ledger-integration Demonstrates how to configure a `setup.py` script for an AEA crypto plug-in. It shows the declaration of specific `setuptools` entry points (`aea.cryptos`, `aea.ledger_apis`, `aea.faucet_apis`) which allow the AEA framework to discover and load the plugin's implementations. ```Python # sample ./setup.py file from setuptools import setup setup( name="open-aea-ledger-myledger", packages=["aea_ledger_myledger"], # plugins must depend on 'aea' install_requires=["aea"], # add other dependencies... # the following makes a plugin available to aea entry_points={ "aea.cryptos": ["myledger = aea_ledger_myledger:MyLedgerCrypto"], "aea.ledger_apis": ["myledger = aea_ledger_myledger:MyLedgerApi"], "aea.faucet_apis": ["myledger = aea_ledger_myledger:MyLedgerFaucetApi"], }, # PyPI classifier for AEA plugins classifiers=["Framework :: AEA"] ) ``` -------------------------------- ### Initial Project Directory and Python Environment Setup Source: https://open-aea.docs.autonolas.tech/quickstart Steps to create a clean working directory for Open-AEA projects and set up a Python virtual environment using pipenv for dependency consistency. ```Shell mkdir my_aea_projects/ && cd my_aea_projects/ ``` ```Shell which pipenv ``` ```Shell touch Pipfile && pipenv --python 3.10 && pipenv shell ``` -------------------------------- ### Install AEA Project Dependencies Source: https://open-aea.docs.autonolas.tech/upgrading This command installs all specified dependencies for an AEA project, including the newly added ledger plugins, into the current Python environment. It should be run after updating the `aea-config.yaml` with the `dependencies` field. ```Shell aea install ``` -------------------------------- ### Prepare AEA Project for Testing Source: https://open-aea.docs.autonolas.tech/quickstart This snippet provides shell commands to set up the AEA project by creating a 'packages' directory, adding a remote protocol, pushing it locally, and cleaning up a previous AEA instance. These steps are crucial before running the end-to-end test. ```Shell mkdir packages cd my_first_aea aea add protocol fetchai/default:1.0.0:bafybeiaf3qhrdttthrisrl2tlpt3mpo5btkozw2dnxlj4cbqq56ilcl6oa --remote aea push protocol fetchai/default --local cd .. aea delete my_aea ``` -------------------------------- ### Get Last Agent Start Status Source: https://open-aea.docs.autonolas.tech/api/manager/manager Retrieves the status of the most recent agent start loading operation, providing details on success, failures, and associated information. ```python @property def last_start_status() -> Tuple[ bool, Dict[PublicId, List[Dict]], List[Tuple[PublicId, List[Dict], Exception]], ] Get status of the last agents start loading state. ``` -------------------------------- ### Start AsyncRuntime Task Source: https://open-aea.docs.autonolas.tech/api/runtime Starts the main runtime task, which includes initiating the multiplexer and the agent's main loop. ```APIDOC AsyncRuntime.run() -> None Starts multiplexer and agent loop. ``` -------------------------------- ### Install AEA Ledger Crypto Plugins Source: https://open-aea.docs.autonolas.tech/p2p-connection Install the necessary `open-aea-ledger-cosmos` and `open-aea-ledger-ethereum` crypto plugins using pip, which are required for ledger interactions and key generation within the AEA framework. ```bash pip install open-aea-ledger-cosmos pip install open-aea-ledger-ethereum ``` -------------------------------- ### Create a New AEA Project Source: https://open-aea.docs.autonolas.tech/http-connection-and-skill This command sequence initializes a new Autonomous Economic Agent (AEA) project named 'my_aea' and navigates into its directory, preparing for further configuration and development. ```bash aea create my_aea cd my_aea ``` -------------------------------- ### Dynamically Register an AEA Behaviour Instance Source: https://open-aea.docs.autonolas.tech/skill This example illustrates how to dynamically register a new Behaviour instance within the skill's code. By adding the behaviour to 'self.context.new_behaviours.put()', it is registered after the AEA setup is complete, bypassing the 'setup' method. ```Python self.context.new_behaviours.put(HelloWorldBehaviour(name="hello_world", skill_context=self.context)) ``` -------------------------------- ### Install AEA Ledger Ethereum Plugin Source: https://open-aea.docs.autonolas.tech/build-aea-programmatically This command installs the 'open-aea-ledger-ethereum' plugin using pip. This plugin is required for interacting with the Ethereum ledger within the AEA framework. ```Bash pip install open-aea-ledger-ethereum ``` -------------------------------- ### Get Behaviour Start Time Source: https://open-aea.docs.autonolas.tech/api/skills/base Retrieves the optional datetime object specifying when the periodical calls for the behaviour should begin. ```Python @property def start_at() -> Optional[datetime.datetime] ``` -------------------------------- ### APIDOC: Execute Pip Command Source: https://open-aea.docs.autonolas.tech/api/helpers/install_dependency Runs a pip install command with specified arguments. Allows setting a timeout and an option to retry the command if it fails. ```APIDOC def call_pip(pip_args: List[str], timeout: float = 300, retry: bool = False) -> None Arguments: pip_args: list strings of the command timeout: timeout to wait pip to install retry: bool, try one more time if command failed ``` -------------------------------- ### Perform Project Load Check Source: https://open-aea.docs.autonolas.tech/api/manager/utils Verifies that the specified project loads correctly. This function is used to ensure the integrity and functionality of a project after installation or setup. ```Python def project_check(project: Project) -> None ``` -------------------------------- ### Create a new AEA project Source: https://open-aea.docs.autonolas.tech/logging This command initializes a new AEA (Autonomous Economic Agent) project with the specified name and navigates into its directory, preparing it for configuration. ```bash aea create my_aea cd my_aea ``` -------------------------------- ### Installing Open-AEA Package with pip Source: https://open-aea.docs.autonolas.tech/quickstart Commands to install the Open-AEA package and its CLI tools using pip, with specific instructions for Bash and Zsh shells to handle special characters in package names. ```Shell echo "$SHELL" ``` ```Shell pip install open-aea[all] pip install open-aea-cli-ipfs ``` ```Shell pip install 'open-aea[all]' pip install 'open-aea-ledger-ethereum' pip install 'open-aea-cli-ipfs' ``` -------------------------------- ### Get protoc compiler version (Python) Source: https://open-aea.docs.autonolas.tech/api/protocols/generator/common Retrieves the version string of the 'protoc' protocol buffer compiler currently installed and in use. This function helps in ensuring compatibility with specific protobuf versions. ```APIDOC def get_protoc_version() -> str Get the protoc version used. ``` -------------------------------- ### Python Function: Get Windows Popen Kwargs Source: https://open-aea.docs.autonolas.tech/api/helpers/base Returns keyword arguments for starting a process in Windows with a new process group, aiding Ctrl+C handling. Returns an empty dict if not on Windows. ```APIDOC def win_popen_kwargs() -> dict Returns: windows popen kwargs ``` -------------------------------- ### Create New AEA Project (Approach 2) Source: https://open-aea.docs.autonolas.tech/development-setup Initialize a new AEA project within your chosen working directory. This command sets up the basic structure for an AEA, allowing you to develop components directly within the project. ```Shell aea create AGENT_NAME && cd AGENT_NAME ``` -------------------------------- ### Install AEA CLI Package Source: https://open-aea.docs.autonolas.tech/cli-how-to Instructions to install only the AEA Command Line Interface package using pip. Includes commands for both bash and zsh shells, addressing quoting differences for shell compatibility. ```bash pip install aea[cli] ``` ```zsh pip install 'aea[cli]' ``` -------------------------------- ### Get Initial State Name (Python Property) Source: https://open-aea.docs.autonolas.tech/api/skills/behaviours Retrieves the name of the initial state for the behavior. This property returns the starting state of the state machine, or None if not set. ```Python @property def initial_state() -> Optional[str] ``` -------------------------------- ### Scaffold a New AEA Skill Source: https://open-aea.docs.autonolas.tech/http-connection-and-skill This command generates the basic directory structure and boilerplate files for a new AEA skill named 'http_echo'. This provides a starting point for implementing custom agent logic. ```bash aea scaffold skill http_echo ``` -------------------------------- ### Populate AEA Agent Inbox (Python) Source: https://open-aea.docs.autonolas.tech/performance-benchmark This code populates the AEA agent's inbox with a specified number of dummy envelopes. This is typically done as a preparation step before starting a benchmark or test. ```Python for _ in range(inbox_amount): aea_test_wrapper.put_inbox(aea_test_wrapper.dummy_envelope()) ``` -------------------------------- ### Create and Navigate AEA Project Source: https://open-aea.docs.autonolas.tech/build-aea-step-by-step Initializes a new AEA project with a specified name and changes the current directory into the newly created project folder, preparing for further configuration. ```Shell aea create my_aea && cd my_aea ``` -------------------------------- ### Python: AEA HTTP Handler for GET, POST, and Invalid Messages Source: https://open-aea.docs.autonolas.tech/http-connection-and-skill Provides Python methods for an AEA handler to process different types of HTTP requests. The snippet demonstrates how to construct and send HTTP responses for GET (implied by the first block) and POST requests, including setting status codes, headers, and body. It also shows how `_handle_invalid` logs warnings for unhandled messages, and `teardown` defines cleanup logic for the handler. ```Python target_message=http_msg, version=http_msg.version, status_code=200, status_text="Success", headers=http_msg.headers, body=json.dumps({"tom": {"type": "cat", "age": 10}}).encode("utf-8"), ) self.context.logger.info("responding with: {}".format(http_response)) self.context.outbox.put_message(message=http_response) def _handle_post(self, http_msg: HttpMessage, http_dialogue: HttpDialogue) -> None: """ Handle a Http request of verb POST. :param http_msg: the http message :param http_dialogue: the http dialogue """ http_response = http_dialogue.reply( performative=HttpMessage.Performative.RESPONSE, target_message=http_msg, version=http_msg.version, status_code=200, status_text="Success", headers=http_msg.headers, body=http_msg.body, ) self.context.logger.info("responding with: {}".format(http_response)) self.context.outbox.put_message(message=http_response) def _handle_invalid( self, http_msg: HttpMessage, http_dialogue: HttpDialogue ) -> None: """ Handle an invalid http message. :param http_msg: the http message :param http_dialogue: the http dialogue """ self.context.logger.warning( "cannot handle http message of performative={} in dialogue={}.".format( http_msg.performative, http_dialogue ) ) def teardown(self) -> None: """Implement the handler teardown.""" ``` -------------------------------- ### Simplified AEA Connection Constructor Source: https://open-aea.docs.autonolas.tech/upgrading Connection constructors now only require implementing the `__init__` method, which receives `configuration`, `identity`, and `crypto_store` as keyword arguments. This simplifies connection development and allows passing key-pairs via `CryptoStore`. ```Python class MyScaffoldConnection(Connection): """Proxy to the functionality of the SDK or API.""" connection_id = PublicId.from_str("fetchai/scaffold:0.1.0") def __init__( self, configuration: ConnectionConfig, identity: Identity, crypto_store: CryptoStore, ): """ Initialize a connection to an SDK or API. :param configuration: the connection configuration. :param crypto_store: object to access the connection crypto objects. :param identity: the identity object. """ super().__init__( configuration=configuration, crypto_store=crypto_store, identity=identity ) ``` -------------------------------- ### AbstractAgent Class API Reference Source: https://open-aea.docs.autonolas.tech/api/abstract_agent Defines the abstract base interface for an agent, including properties for name and storage URI, and methods for agent lifecycle (start, stop, setup, teardown), periodic actions (act), message handling (handle_envelope, get_message_handlers), task scheduling (get_periodic_tasks), and exception handling. ```APIDOC AbstractAgent(ABC): Description: This class provides an abstract base interface for an agent. Signature: class AbstractAgent(ABC) Properties: name: Signature: @property\n@abstractmethod\ndef name() -> str Description: Get agent's name. storage_uri: Signature: @property\n@abstractmethod\ndef storage_uri() -> Optional[str] Description: Return storage uri. Methods: start: Signature: @abstractmethod\ndef start() -> None Description: Start the agent. Returns: None stop: Signature: @abstractmethod\ndef stop() -> None Description: Stop the agent. Returns: None setup: Signature: @abstractmethod\ndef setup() -> None Description: Set up the agent. Returns: None act: Signature: @abstractmethod\ndef act() -> None Description: Perform actions on period. Returns: None handle_envelope: Signature: @abstractmethod\ndef handle_envelope(envelope: Envelope) -> None Description: Handle an envelope. Parameters: envelope: the envelope to handle. Returns: None get_periodic_tasks: Signature: @abstractmethod\ndef get_periodic_tasks(\n) -> Dict[Callable, Tuple[float, Optional[datetime.datetime]]] Description: Get all periodic tasks for agent. Returns: dict of callable with period specified get_message_handlers: Signature: @abstractmethod\ndef get_message_handlers() -> List[Tuple[Callable[[Any], None], Callable]] Description: Get handlers with message getters. Returns: List of tuples of callables: handler and coroutine to get a message exception_handler: Signature: @abstractmethod\ndef exception_handler(exception: Exception,\n function: Callable) -> Optional[bool] Description: Handle exception raised during agent main loop execution. Parameters: exception: exception raised function: a callable exception raised in. Returns: skip exception if True, otherwise re-raise it teardown: Signature: @abstractmethod\ndef teardown() -> None Description: Tear down the agent. Returns: None ``` -------------------------------- ### Create a New AEA Project Source: https://open-aea.docs.autonolas.tech/quickstart These commands initialize a new Autonomous Economic Agent (AEA) project with a specified name and then navigate into the newly created project directory. This is the first step in developing a new AEA. ```bash aea create my_first_aea cd my_first_aea ``` -------------------------------- ### Open-AEA API Module and Plugin Reference Source: https://open-aea.docs.autonolas.tech/development-setup Provides a comprehensive, hierarchical listing of all documented API modules and plugins within the Open-AEA framework, including core utilities, CLI tools (IPFS, Benchmark), and ledger integrations (Cosmos, Ethereum, Fetchai). Each entry points to its respective API documentation path. ```APIDOC - Network: ../api/test_tools/network/ - Utils: ../api/test_tools/utils/ - Plugins - CLI - IPFS - API: ../api/plugins/aea_cli_ipfs/core/ - Exceptions: ../api/plugins/aea_cli_ipfs/exceptions/ - Registry: ../api/plugins/aea_cli_ipfs/registry/ - Utils: ../api/plugins/aea_cli_ipfs/ipfs_utils/ - Test Tools: ../api/plugins/aea_cli_ipfs/test_tools/fixture_helpers/ - Benchmark - Core: ../api/plugins/aea_cli_benchmark/core/ - Utils: ../api/plugins/aea_cli_benchmark/utils/ - Cases - ACN Communication - Base: ../api/plugins/aea_cli_benchmark/case_acn_communication/case/ - Command: ../api/plugins/aea_cli_benchmark/case_acn_communication/command/ - Utils: ../api/plugins/aea_cli_benchmark/case_acn_communication/utils/ - ACN Startup - Base: ../api/plugins/aea_cli_benchmark/case_acn_startup/case/ - Command: ../api/plugins/aea_cli_benchmark/case_acn_startup/command/ - Utils: ../api/plugins/aea_cli_benchmark/case_acn_startup/utils/ - Agent Construction - Base: ../api/plugins/aea_cli_benchmark/case_agent_construction_time/case/ - Command: ../api/plugins/aea_cli_benchmark/case_agent_construction_time/command/ - Decision Maker - Base: ../api/plugins/aea_cli_benchmark/case_decision_maker/case/ - Command: ../api/plugins/aea_cli_benchmark/case_decision_maker/command/ - Dialogues Memory Usage - Base: ../api/plugins/aea_cli_benchmark/case_dialogues_memory_usage/case/ - Command: ../api/plugins/aea_cli_benchmark/case_dialogues_memory_usage/command/ - Memory Usage - Base: ../api/plugins/aea_cli_benchmark/case_mem_usage/case/ - Command: ../api/plugins/aea_cli_benchmark/case_mem_usage/command/ - Messages Memory Usage - Base: ../api/plugins/aea_cli_benchmark/case_messages_memory_usage/case/ - Command: ../api/plugins/aea_cli_benchmark/case_messages_memory_usage/command/ - Multiagent - Base: ../api/plugins/aea_cli_benchmark/case_multiagent/case/ - Command: ../api/plugins/aea_cli_benchmark/case_multiagent/command/ - Multiagent HTTP Dialogues - Base: ../api/plugins/aea_cli_benchmark/case_multiagent_http_dialogues/case/ - Command: ../api/plugins/aea_cli_benchmark/case_multiagent_http_dialogues/command/ - Proactive - Base: ../api/plugins/aea_cli_benchmark/case_proactive/case/ - Command: ../api/plugins/aea_cli_benchmark/case_proactive/command/ - Reactive - Base: ../api/plugins/aea_cli_benchmark/case_reactive/case/ - Command: ../api/plugins/aea_cli_benchmark/case_reactive/command/ - Transaction Generation - Base: ../api/plugins/aea_cli_benchmark/case_tx_generate/case/ - Core: ../api/plugins/aea_cli_benchmark/case_tx_generate/core/ - Command: ../api/plugins/aea_cli_benchmark/case_tx_generate/command/ - Dialogues: ../api/plugins/aea_cli_benchmark/case_tx_generate/dialogues/ - Docker Image: ../api/plugins/aea_cli_benchmark/case_tx_generate/docker_image/ - Ledger Utils: ../api/plugins/aea_cli_benchmark/case_tx_generate/ledger_utils/ - Ledger - Cosmos - API: ../api/plugins/aea_ledger_cosmos/cosmos/ - HashFuncs: ../api/plugins/aea_ledger_cosmos/hashfuncs/ - Ethereum - API: ../api/plugins/aea_ledger_ethereum/ethereum/ - Constants: ../api/plugins/aea_ledger_ethereum/test_tools/constants/ - Docker Images: ../api/plugins/aea_ledger_ethereum/test_tools/docker_images/ - Fixture Helpers: ../api/plugins/aea_ledger_ethereum/test_tools/fixture_helpers/ - Fetchai - API: ../api/plugins/aea_ledger_fetchai/fetchai/ - Constants: ../api/plugins/aea_ledger_fetchai/test_tools/constants/ - Docker Images: ../api/plugins/aea_ledger_fetchai/test_tools/docker_images/ - HashFuncs: ../api/plugins/aea_ledger_fetchai/hashfuncs/ - Registries: ../api/registries/ ``` -------------------------------- ### Create a new AEA project and navigate into its directory Source: https://open-aea.docs.autonolas.tech/scaffolding This command sequence initializes a new Autonomous Economic Agent (AEA) project with a specified author and then changes the current directory into the newly created project. This is the essential first step before scaffolding any specific AEA packages. ```bash aea create my_aea --author "fetchai" cd my_aea ``` -------------------------------- ### Agent start Method Source: https://open-aea.docs.autonolas.tech/api/agent Starts the agent. Performs the following: * calls start() on runtime. * waits for runtime to complete running (blocking) ```APIDOC start() -> None ``` -------------------------------- ### Python Class Method: setup_class Source: https://open-aea.docs.autonolas.tech/api/test_tools/test_cases This class method is used to set up the test class, preparing the environment before any tests in the class are run. It is typically invoked once before all tests in the class begin. ```python @classmethod def setup_class(cls) -> None ``` -------------------------------- ### Initialize AsyncRuntime Source: https://open-aea.docs.autonolas.tech/api/runtime Initializes the asynchronous runtime instance, setting up the agent, multiplexer options, loop mode, and task manager mode. This constructor is identical to `BaseRuntime`'s. ```APIDOC AsyncRuntime.__init__(agent: AbstractAgent, multiplexer_options: Dict, loop_mode: Optional[str] = None, loop: Optional[AbstractEventLoop] = None, threaded: bool = False, task_manager_mode: Optional[str] = None) -> None agent: Agent to run. multiplexer_options: options for the multiplexer. loop_mode: agent main loop mode. loop: optional event loop. if not provided a new one will be created. threaded: if True, run in threaded mode, else async task_manager_mode: mode of the task manager. ``` -------------------------------- ### Find Reachable Nodes in a Graph Source: https://open-aea.docs.autonolas.tech/api/helpers/base Identifies and returns the subgraph induced by a set of starting nodes, containing all nodes reachable from those starting points. It takes the adjacency list of the full graph and a set of starting nodes as input. ```Python def reachable_nodes(adjacency_list: Dict[T, Set[T]], starting_nodes: Set[T]) -> Dict[T, Set[T]] ``` -------------------------------- ### Create and Build Genesis AEA for P2P Network Source: https://open-aea.docs.autonolas.tech/p2p-connection Initialize the first AEA, `my_genesis_aea`, navigate into its directory, add the `valory/p2p_libp2p` connection, set it as the default connection, install its dependencies, and build the agent for the Agent Communication Network (ACN). ```bash aea create my_genesis_aea cd my_genesis_aea aea add connection valory/p2p_libp2p:0.1.0:bafybeig2atkjnrz7lsboubaque567ndtzog6k53dnmrrq3eeqgbqmmcq5y --remote aea config set agent.default_connection valory/p2p_libp2p:0.1.0 aea install aea build ``` -------------------------------- ### Python: Get Contract Instance Source: https://open-aea.docs.autonolas.tech/api/plugins/aea_ledger_ethereum/ethereum Get the instance of a contract. ```Python def get_contract_instance(contract_interface: Dict[str, str], contract_address: Optional[str] = None) -> Any ``` ```APIDOC Function: get_contract_instance Purpose: Get the instance of a contract. Arguments: contract_interface: Dict[str, str] - the contract interface. contract_address: Optional[str] - the contract address. Returns: Any - the contract instance ``` -------------------------------- ### Python: Get Transaction Source: https://open-aea.docs.autonolas.tech/api/plugins/aea_ledger_ethereum/ethereum Get the transaction for a transaction digest. ```Python def get_transaction(tx_digest: str, raise_on_try: bool = False) -> Optional[JSONLike] ``` ```APIDOC Function: get_transaction Purpose: Get the transaction for a transaction digest. Arguments: tx_digest: str - the digest associated to the transaction. raise_on_try: bool - whether the method will raise or log on error Returns: Optional[JSONLike] - the tx, if present ``` -------------------------------- ### Create New AEA Project Source: https://open-aea.docs.autonolas.tech/protocol-generator Instructions to initialize a new Autonomous Economic Agent (AEA) project and navigate into its newly created directory. ```bash aea create my_aea cd my_aea ``` -------------------------------- ### AbstractMultipleExecutor start Method Source: https://open-aea.docs.autonolas.tech/api/helpers/multiple_executor Starts the execution of all tasks managed by the executor. ```APIDOC def start() -> None ``` -------------------------------- ### Build ACN Go Peer Node Locally Source: https://open-aea.docs.autonolas.tech/p2p-connection Commands to clone the `open-acn` repository, navigate into it, build the `libp2p_node` binary using Go, and make it executable. This prepares the standalone peer node for local execution. ```bash git clone https://github.com/valory-xyz/open-acn/ cd open-acn go build chmod +x libp2p_node ``` -------------------------------- ### Python: Get Transaction Receipt Source: https://open-aea.docs.autonolas.tech/api/plugins/aea_ledger_ethereum/ethereum Get the transaction receipt for a transaction digest. ```Python def get_transaction_receipt(tx_digest: str, raise_on_try: bool = False) -> Optional[JSONLike] ``` ```APIDOC Function: get_transaction_receipt Purpose: Get the transaction receipt for a transaction digest. Arguments: tx_digest: str - the digest associated to the transaction. raise_on_try: bool - whether the method will raise or log on error Returns: Optional[JSONLike] - the tx receipt, if present ``` -------------------------------- ### Storage.run Method Source: https://open-aea.docs.autonolas.tech/api/helpers/storage/generic_storage Asynchronously initiates the connection process for the storage. This method is responsible for establishing the underlying storage link. ```APIDOC async def run() -> None ``` -------------------------------- ### FetchAIApi Initialization Method Source: https://open-aea.docs.autonolas.tech/api/plugins/aea_ledger_fetchai/fetchai Initializes the Fetch.ai ledger API instance. ```Python FetchAIApi.__init__(**kwargs: Any) -> None ``` -------------------------------- ### Full Python script for AEA setup and message handling Source: https://open-aea.docs.autonolas.tech/build-aea-programmatically This script initializes an AEA, creates an Ethereum private key, and configures the agent with essential components like protocols, connections, and skills. It also includes a custom handler to process messages and demonstrates sending an input message and reading an output response via file operations, showcasing basic AEA interaction. It depends on `aea` and `aea_ledger_ethereum` packages and assumes local `packages/fetchai` for default components. ```Python import os import time from threading import Thread from aea_ledger_ethereum import EthereumCrypto from aea.aea_builder import AEABuilder from aea.configurations.base import SkillConfig from aea.crypto.helpers import PRIVATE_KEY_PATH_SCHEMA, create_private_key from aea.helpers.file_io import write_with_lock from aea.skills.base import Skill ROOT_DIR = "./" INPUT_FILE = "input_file" OUTPUT_FILE = "output_file" PRIVATE_KEY_FILE = PRIVATE_KEY_PATH_SCHEMA.format(EthereumCrypto.identifier) def run(): """Run demo.""" # Create a private key create_private_key(EthereumCrypto.identifier, PRIVATE_KEY_FILE) # Ensure the input and output files do not exist initially if os.path.isfile(INPUT_FILE): os.remove(INPUT_FILE) if os.path.isfile(OUTPUT_FILE): os.remove(OUTPUT_FILE) # Instantiate the builder and build the AEA # By default, the default protocol, error skill and stub connection are added builder = AEABuilder() builder.set_name("my_aea") builder.add_private_key(EthereumCrypto.identifier, PRIVATE_KEY_FILE) # Add the default protocol (assuming it is present in the local directory 'packages') builder.add_protocol("./packages/fetchai/protocols/default") # Add the stub connection (assuming it is present in the local directory 'packages') builder.add_connection("./packages/fetchai/connections/stub") # Add the echo skill (assuming it is present in the local directory 'packages') builder.add_skill("./packages/fetchai/skills/echo") # create skill and handler manually from aea.protocols.base import Message from aea.skills.base import Handler from packages.fetchai.protocols.default.message import DefaultMessage class DummyHandler(Handler): """Dummy handler to handle messages.""" SUPPORTED_PROTOCOL = DefaultMessage.protocol_id def setup(self) -> None: """Noop setup.""" def teardown(self) -> None: """Noop teardown.""" def handle(self, message: Message) -> None: """Handle incoming message.""" self.context.logger.info("You got a message: {}".format(str(message))) config = SkillConfig(name="test_skill", author="fetchai") skill = Skill(configuration=config) dummy_handler = DummyHandler( name="dummy_handler", skill_context=skill.skill_context ) skill.handlers.update({dummy_handler.name: dummy_handler}) builder.add_component_instance(skill) # Create our AEA my_aea = builder.build() # Set the AEA running in a different thread try: t = Thread(target=my_aea.start) t.start() # Wait for everything to start up time.sleep(4) # Create a message inside an envelope and get the stub connection to pass it on to the echo skill message_text = b"my_aea,other_agent,fetchai/default:1.0.0,\x12\x10\x08\x01\x12\x011*\t*\x07\n\x05hello," with open(INPUT_FILE, "wb") as f: write_with_lock(f, message_text) print(b"input message: " + message_text) # Wait for the envelope to get processed time.sleep(4) # Read the output envelope generated by the echo skill with open(OUTPUT_FILE, "rb") as f: print(b"output message: " + f.readline()) finally: # Shut down the AEA my_aea.stop() t.join() t = None if __name__ == "__main__": run() ``` -------------------------------- ### List Installed AEA Resources Source: https://open-aea.docs.autonolas.tech/cli-commands Lists the installed resources, optionally filtered by a specific package type. ```CLI list [package_type] ``` -------------------------------- ### Python: Try Get Gas Pricing Source: https://open-aea.docs.autonolas.tech/api/plugins/aea_ledger_ethereum/ethereum Try get the gas price based on the provided strategy. ```Python @try_decorator("Unable to retrieve gas price: {}", logger_method="warning") def try_get_gas_pricing(gas_price_strategy: Optional[str] = None, extra_config: Optional[Dict] = None, old_price: Optional[Dict[str, Wei]] = None, **_kwargs: Any) -> Optional[Dict[str, Wei]] ``` ```APIDOC Function: try_get_gas_pricing Purpose: Try get the gas price based on the provided strategy. Arguments: gas_price_strategy: Optional[str] - the gas price strategy to use, e.g., the EIP-1559 strategy. Can be either eip1559 or gas_station. extra_config: Optional[Dict] - gas price strategy getter parameters. old_price: Optional[Dict[str, Wei]] - the old gas price params in case that we are trying to resubmit a transaction. _kwargs: Any - the keyword arguments. Possible kwargs are: raise_on_try: bool flag specifying whether the method will raise or log on error (used by try_decorator) Returns: Optional[Dict[str, Wei]] - a dictionary with the gas data. ``` -------------------------------- ### Initialize AEA Handler Setup Source: https://open-aea.docs.autonolas.tech/decision-maker-transaction Implements the setup logic for the handler, preparing it for operation. This method is called once when the handler is initialized. ```python def setup(self) -> None: """Implement the setup for the handler.""" ```