Пример #1
0
    def setup_class(cls):
        """Set the test up."""
        agent_name = "my_agent"
        private_key_path = os.path.join(CUR_PATH, "data",
                                        "fet_private_key.txt")
        wallet = Wallet({FETCHAI: private_key_path})
        identity = Identity(agent_name, address=wallet.addresses[FETCHAI])
        connection = _make_local_connection(identity.address, LocalNode())
        resources = Resources()
        cls.context_namespace = {"key1": 1, "key2": 2}
        cls.agent = AEA(identity, wallet, resources, **cls.context_namespace)

        resources.add_connection(connection)
        resources.add_component(
            Skill.from_dir(Path(CUR_PATH, "data", "dummy_skill"),
                           agent_context=cls.agent.context))
        for skill in resources.get_all_skills():
            skill.skill_context.set_agent_context(cls.agent.context)
Пример #2
0
def test_add_behaviour_dynamically():
    """Test that we can add a behaviour dynamically."""

    agent_name = "MyAgent"
    private_key_path = os.path.join(CUR_PATH, "data", "fet_private_key.txt")
    wallet = Wallet({FETCHAI: private_key_path})
    resources = Resources()
    identity = Identity(agent_name, address=wallet.addresses[FETCHAI])
    connection = _make_local_connection(identity.address, LocalNode())
    agent = AEA(
        identity,
        wallet,
        resources,
        default_connection=connection.public_id,
    )
    resources.add_connection(connection)
    resources.add_component(
        Skill.from_dir(Path(CUR_PATH, "data", "dummy_skill"),
                       agent_context=agent.context))
    for skill in resources.get_all_skills():
        skill.skill_context.set_agent_context(agent.context)

    with run_in_thread(agent.start, timeout=5, on_exit=agent.stop):
        wait_for_condition(
            lambda: agent._main_loop and agent._main_loop.is_running,
            timeout=10)

        dummy_skill_id = PublicId("dummy_author", "dummy", "0.1.0")
        dummy_skill = agent.resources.get_skill(dummy_skill_id)

        wait_for_condition(lambda: dummy_skill is not None, timeout=10)

        new_behaviour = DummyBehaviour(name="dummy2",
                                       skill_context=dummy_skill.skill_context)
        dummy_skill.skill_context.new_behaviours.put(new_behaviour)

        wait_for_condition(lambda: new_behaviour.nb_act_called > 0, timeout=10)
        wait_for_condition(
            lambda: len(agent.resources.get_behaviours(dummy_skill_id)) == 2,
            timeout=10)
Пример #3
0
def test_add_behaviour_dynamically():
    """Test that we can add a behaviour dynamically."""
    agent_name = "MyAgent"
    private_key_path = os.path.join(CUR_PATH, "data", DEFAULT_PRIVATE_KEY_FILE)
    wallet = Wallet({DEFAULT_LEDGER: private_key_path})
    resources = Resources()
    identity = Identity(agent_name, address=wallet.addresses[DEFAULT_LEDGER])
    connection = _make_local_connection(identity.address, LocalNode())
    agent = AEA(
        identity,
        wallet,
        resources,
        default_connection=connection.public_id,
    )
    resources.add_connection(connection)
    resources.add_component(
        Skill.from_dir(Path(CUR_PATH, "data", "dummy_skill"),
                       agent_context=agent.context))
    for skill in resources.get_all_skills():
        skill.skill_context.set_agent_context(agent.context)

    with run_in_thread(agent.start, timeout=5, on_exit=agent.stop):
        wait_for_condition(lambda: agent.is_running, timeout=10)

        dummy_skill_id = DUMMY_SKILL_PUBLIC_ID
        dummy_skill = agent.resources.get_skill(dummy_skill_id)

        wait_for_condition(lambda: dummy_skill is not None, timeout=10)

        new_behaviour = DummyBehaviour(name="dummy2",
                                       skill_context=dummy_skill.skill_context)
        dummy_skill.skill_context.new_behaviours.put(new_behaviour)

        wait_for_condition(lambda: new_behaviour.nb_act_called > 0, timeout=10)
        wait_for_condition(
            lambda: len(agent.resources.get_behaviours(dummy_skill_id)) == 2,
            timeout=10)
Пример #4
0
    def setup_class(cls, decision_maker_handler_class=None):
        """Test the initialisation of the AEA."""
        cls.wallet = Wallet({
            FETCHAI: FETCHAI_PRIVATE_KEY_PATH,
            ETHEREUM: ETHEREUM_PRIVATE_KEY_PATH
        })
        cls.connection = _make_dummy_connection()
        resources = Resources()
        resources.add_connection(cls.connection)
        cls.identity = Identity(
            "name",
            addresses=cls.wallet.addresses,
            default_address_key=FETCHAI,
        )
        cls.my_aea = AEA(
            cls.identity,
            cls.wallet,
            data_dir=MagicMock(),
            resources=resources,
            decision_maker_handler_class=decision_maker_handler_class,
        )

        cls.skill_context = SkillContext(cls.my_aea.context,
                                         skill=MagicMock(contracts={}))
Пример #5
0
def test_initialize_aea_programmatically_build_resources():
    """Test that we can initialize the agent by building the resource object."""
    try:
        temp = tempfile.mkdtemp(prefix="test_aea_resources")
        with LocalNode() as node:
            agent_name = "MyAgent"
            private_key_path = os.path.join(CUR_PATH, "data",
                                            DEFAULT_PRIVATE_KEY_FILE)
            wallet = Wallet({DEFAULT_LEDGER: private_key_path})
            identity = Identity(agent_name,
                                address=wallet.addresses[DEFAULT_LEDGER])
            connection = _make_local_connection(agent_name, node)

            resources = Resources()
            aea = AEA(
                identity,
                wallet,
                resources=resources,
                default_connection=connection.public_id,
            )

            default_protocol = Protocol.from_dir(
                str(Path(AEA_DIR, "protocols", "default")))
            resources.add_protocol(default_protocol)
            resources.add_connection(connection)

            error_skill = Skill.from_dir(str(Path(AEA_DIR, "skills", "error")),
                                         agent_context=aea.context)
            dummy_skill = Skill.from_dir(str(
                Path(CUR_PATH, "data", "dummy_skill")),
                                         agent_context=aea.context)
            resources.add_skill(dummy_skill)
            resources.add_skill(error_skill)

            default_protocol_id = DefaultMessage.protocol_id

            expected_message = DefaultMessage(
                dialogue_reference=("", ""),
                message_id=1,
                target=0,
                performative=DefaultMessage.Performative.BYTES,
                content=b"hello",
            )
            expected_message.counterparty = agent_name
            expected_message.sender = agent_name

            with run_in_thread(aea.start, timeout=5, on_exit=aea.stop):
                wait_for_condition(lambda: aea.is_running, timeout=10)
                aea.outbox.put(
                    Envelope(
                        to=agent_name,
                        sender=agent_name,
                        protocol_id=default_protocol_id,
                        message=expected_message,
                    ))

                dummy_skill_id = DUMMY_SKILL_PUBLIC_ID
                dummy_behaviour_name = "dummy"
                dummy_behaviour = aea.resources.get_behaviour(
                    dummy_skill_id, dummy_behaviour_name)
                wait_for_condition(lambda: dummy_behaviour is not None,
                                   timeout=10)
                wait_for_condition(lambda: dummy_behaviour.nb_act_called > 0,
                                   timeout=10)

                dummy_task = DummyTask()
                task_id = aea.task_manager.enqueue_task(dummy_task)
                async_result = aea.task_manager.get_task_result(task_id)
                expected_dummy_task = async_result.get(10.0)
                wait_for_condition(
                    lambda: expected_dummy_task.nb_execute_called > 0,
                    timeout=10)
                dummy_handler_name = "dummy"
                dummy_handler = aea.resources._handler_registry.fetch(
                    (dummy_skill_id, dummy_handler_name))
                dummy_handler_alt = aea.resources.get_handler(
                    DefaultMessage.protocol_id, dummy_skill_id)
                wait_for_condition(lambda: dummy_handler == dummy_handler_alt,
                                   timeout=10)
                wait_for_condition(lambda: dummy_handler is not None,
                                   timeout=10)
                wait_for_condition(
                    lambda: len(dummy_handler.handled_messages) == 1,
                    timeout=10)
                wait_for_condition(
                    lambda: dummy_handler.handled_messages[0] ==
                    expected_message,
                    timeout=10,
                )
    finally:
        Path(temp).rmdir()
    async def test_end_to_end_aea_aca(self):
        """Test the end to end aea aca interaction."""
        # AEA components
        wallet = Wallet({DEFAULT_LEDGER: DEFAULT_PRIVATE_KEY_FILE})
        identity = Identity(
            name="my_aea_1",
            address=wallet.addresses.get(DEFAULT_LEDGER),
            default_address_key=DEFAULT_LEDGER,
        )
        configuration = ConnectionConfig(
            host=self.aca_admin_address,
            port=self.aca_admin_port,
            connection_id=HTTPClientConnection.connection_id,
        )
        http_client_connection = HTTPClientConnection(
            configuration=configuration,
            identity=identity,
        )
        resources = Resources()
        resources.add_connection(http_client_connection)

        # create AEA
        aea = AEA(identity, wallet, resources)

        # Add http protocol to AEA resources
        http_protocol_configuration = ProtocolConfig.from_json(
            yaml.safe_load(
                open(
                    os.path.join(
                        self.cwd,
                        "packages",
                        "fetchai",
                        "protocols",
                        "http",
                        "protocol.yaml",
                    ))))
        http_protocol = Protocol(http_protocol_configuration,
                                 HttpMessage.serializer())
        resources.add_protocol(http_protocol)

        # Request message & envelope
        request_http_message = HttpMessage(
            dialogue_reference=("", ""),
            target=0,
            message_id=1,
            performative=HttpMessage.Performative.REQUEST,
            method="GET",
            url="http://{}:{}/status".format(self.aca_admin_address,
                                             self.aca_admin_port),
            headers="",
            version="",
            body=b"",
        )
        request_http_message.to = "ACA"
        request_envelope = Envelope(
            to="ACA",
            sender="AEA",
            protocol_id=HttpMessage.protocol_id,
            message=request_http_message,
        )

        # add a simple skill with handler
        skill_context = SkillContext(aea.context)
        skill_config = SkillConfig(name="simple_skill",
                                   author="fetchai",
                                   version="0.1.0")
        aea_handler = AEAHandler(skill_context=skill_context,
                                 name="aea_handler")
        simple_skill = Skill(skill_config,
                             skill_context,
                             handlers={aea_handler.name: aea_handler})
        resources.add_skill(simple_skill)

        # add error skill to AEA
        error_skill = Skill.from_dir(os.path.join(AEA_DIR, "skills", "error"),
                                     agent_context=aea.context)
        resources.add_skill(error_skill)

        # start AEA thread
        t_aea = Thread(target=aea.start)
        try:
            t_aea.start()
            time.sleep(1.0)
            aea.outbox.put(request_envelope)
            time.sleep(5.0)
            assert (aea_handler.handled_message.performative ==
                    HttpMessage.Performative.RESPONSE)
            assert aea_handler.handled_message.version == ""
            assert aea_handler.handled_message.status_code == 200
            assert aea_handler.handled_message.status_text == "OK"
            assert aea_handler.handled_message.headers is not None
            assert aea_handler.handled_message.version is not None
        finally:
            aea.stop()
            t_aea.join()
Пример #7
0
def run():
    # Create a private key
    create_private_key(CosmosCrypto.identifier)

    # Set up the wallet, identity and (empty) resources
    wallet = Wallet(
        private_key_paths={CosmosCrypto.identifier: COSMOS_PRIVATE_KEY_FILE},
        connection_private_key_paths={CosmosCrypto.identifier: COSMOS_PRIVATE_KEY_FILE},
    )
    identity = Identity("my_aea", address=wallet.addresses.get(CosmosCrypto.identifier))
    resources = Resources()

    # specify the default routing for some protocols
    default_routing = {
        PublicId.from_str("fetchai/ledger_api:0.1.0"): LedgerConnection.connection_id,
        PublicId.from_str("fetchai/oef_search:0.3.0"): SOEFConnection.connection_id,
    }
    default_connection = SOEFConnection.connection_id

    # create the AEA
    my_aea = AEA(
        identity,
        wallet,
        resources,
        default_connection=default_connection,
        default_routing=default_routing,
    )

    # Add the default protocol (which is part of the AEA distribution)
    default_protocol = Protocol.from_dir(os.path.join(AEA_DIR, "protocols", "default"))
    resources.add_protocol(default_protocol)

    # Add the signing protocol (which is part of the AEA distribution)
    signing_protocol = Protocol.from_dir(os.path.join(AEA_DIR, "protocols", "signing"))
    resources.add_protocol(signing_protocol)

    # Add the ledger_api protocol
    ledger_api_protocol = Protocol.from_dir(
        os.path.join(os.getcwd(), "packages", "fetchai", "protocols", "ledger_api",)
    )
    resources.add_protocol(ledger_api_protocol)

    # Add the oef_search protocol
    oef_protocol = Protocol.from_dir(
        os.path.join(os.getcwd(), "packages", "fetchai", "protocols", "oef_search",)
    )
    resources.add_protocol(oef_protocol)

    # Add the fipa protocol
    fipa_protocol = Protocol.from_dir(
        os.path.join(os.getcwd(), "packages", "fetchai", "protocols", "fipa",)
    )
    resources.add_protocol(fipa_protocol)

    # Add the LedgerAPI connection
    configuration = ConnectionConfig(connection_id=LedgerConnection.connection_id)
    ledger_api_connection = LedgerConnection(
        configuration=configuration, identity=identity
    )
    resources.add_connection(ledger_api_connection)

    # Add the P2P connection
    configuration = ConnectionConfig(
        connection_id=P2PLibp2pConnection.connection_id,
        delegate_uri="127.0.0.1:11001",
        entry_peers=[ENTRY_PEER_ADDRESS],
        local_uri="127.0.0.1:9001",
        log_file="libp2p_node.log",
        public_uri="127.0.0.1:9001",
    )
    p2p_connection = P2PLibp2pConnection(
        configuration=configuration,
        identity=identity,
        crypto_store=wallet.connection_cryptos,
    )
    resources.add_connection(p2p_connection)

    # Add the SOEF connection
    configuration = ConnectionConfig(
        api_key=API_KEY,
        soef_addr=SOEF_ADDR,
        soef_port=SOEF_PORT,
        restricted_to_protocols={PublicId.from_str("fetchai/oef_search:0.3.0")},
        connection_id=SOEFConnection.connection_id,
        delegate_uri="127.0.0.1:11001",
        entry_peers=[ENTRY_PEER_ADDRESS],
        local_uri="127.0.0.1:9001",
        log_file="libp2p_node.log",
        public_uri="127.0.0.1:9001",
    )
    soef_connection = SOEFConnection(configuration=configuration, identity=identity)
    resources.add_connection(soef_connection)

    # Add the error and weather_client skills
    error_skill = Skill.from_dir(
        os.path.join(AEA_DIR, "skills", "error"), agent_context=my_aea.context
    )
    weather_skill = Skill.from_dir(
        os.path.join(ROOT_DIR, "packages", "fetchai", "skills", "weather_client"),
        agent_context=my_aea.context,
    )

    strategy = cast(Strategy, weather_skill.models.get("strategy"))
    strategy._is_ledger_tx = False

    for skill in [error_skill, weather_skill]:
        resources.add_skill(skill)

    # Run the AEA
    try:
        logger.info("STARTING AEA NOW!")
        my_aea.start()
    except KeyboardInterrupt:
        logger.info("STOPPING AEA NOW!")
        my_aea.stop()
Пример #8
0
def run():
    """Run demo."""

    # Create a private key
    create_private_key(FetchAICrypto.identifier, FETCHAI_PRIVATE_KEY_FILE)
    create_private_key(FetchAICrypto.identifier, FETCHAI_PRIVATE_KEY_FILE_CONNECTION)

    # Set up the wallet, identity and (empty) resources
    wallet = Wallet(
        private_key_paths={FetchAICrypto.identifier: FETCHAI_PRIVATE_KEY_FILE},
        connection_private_key_paths={
            FetchAICrypto.identifier: FETCHAI_PRIVATE_KEY_FILE_CONNECTION
        },
    )
    identity = Identity(
        "my_aea", address=wallet.addresses.get(FetchAICrypto.identifier)
    )
    resources = Resources()
    data_dir = os.getcwd()

    # specify the default routing for some protocols
    default_routing = {
        LedgerApiMessage.protocol_id: LedgerConnection.connection_id,
        OefSearchMessage.protocol_id: SOEFConnection.connection_id,
    }
    default_connection = P2PLibp2pConnection.connection_id

    state_update_protocol = Protocol.from_dir(
        os.path.join(os.getcwd(), "packages", "fetchai", "protocols", "state_update")
    )
    resources.add_protocol(state_update_protocol)

    # Add the default protocol (which is part of the AEA distribution)
    default_protocol = Protocol.from_dir(
        os.path.join(os.getcwd(), "packages", "fetchai", "protocols", "default")
    )
    resources.add_protocol(default_protocol)

    # Add the signing protocol (which is part of the AEA distribution)
    signing_protocol = Protocol.from_dir(
        os.path.join(os.getcwd(), "packages", "fetchai", "protocols", "signing")
    )
    resources.add_protocol(signing_protocol)

    # Add the ledger_api protocol
    ledger_api_protocol = Protocol.from_dir(
        os.path.join(os.getcwd(), "packages", "fetchai", "protocols", "ledger_api",)
    )
    resources.add_protocol(ledger_api_protocol)

    # Add the oef_search protocol
    oef_protocol = Protocol.from_dir(
        os.path.join(os.getcwd(), "packages", "fetchai", "protocols", "oef_search",)
    )
    resources.add_protocol(oef_protocol)

    # Add the fipa protocol
    fipa_protocol = Protocol.from_dir(
        os.path.join(os.getcwd(), "packages", "fetchai", "protocols", "fipa",)
    )
    resources.add_protocol(fipa_protocol)

    # Add the LedgerAPI connection
    configuration = ConnectionConfig(connection_id=LedgerConnection.connection_id)
    ledger_api_connection = LedgerConnection(
        configuration=configuration, data_dir=data_dir, identity=identity
    )
    resources.add_connection(ledger_api_connection)

    # Add the P2P connection
    cert_path = ".certs/conn_cert.txt"
    cert_request = CertRequest(
        identifier="acn",
        ledger_id=FetchAICrypto.identifier,
        not_after="2022-01-01",
        not_before="2021-01-01",
        public_key="fetchai",
        save_path=cert_path,
    )
    public_key = wallet.connection_cryptos.public_keys.get(FetchAICrypto.identifier)
    message = cert_request.get_message(public_key)
    make_certificate(
        FetchAICrypto.identifier, FETCHAI_PRIVATE_KEY_FILE, message, cert_path
    )
    configuration = ConnectionConfig(
        connection_id=P2PLibp2pConnection.connection_id,
        delegate_uri="127.0.0.1:11001",
        entry_peers=[ENTRY_PEER_ADDRESS],
        local_uri="127.0.0.1:9001",
        log_file="libp2p_node.log",
        public_uri="127.0.0.1:9001",
        build_directory=os.getcwd(),
        build_entrypoint="check_dependencies.py",
        cert_requests=[cert_request],
    )
    configuration.directory = os.path.dirname(
        packages.fetchai.connections.p2p_libp2p.connection.__file__
    )

    AEABuilder.run_build_for_component_configuration(configuration)

    p2p_connection = P2PLibp2pConnection(
        configuration=configuration,
        data_dir=data_dir,
        identity=identity,
        crypto_store=wallet.connection_cryptos,
    )
    resources.add_connection(p2p_connection)

    # Add the SOEF connection
    configuration = ConnectionConfig(
        api_key=API_KEY,
        soef_addr=SOEF_ADDR,
        soef_port=SOEF_PORT,
        restricted_to_protocols={OefSearchMessage.protocol_id},
        connection_id=SOEFConnection.connection_id,
    )
    soef_connection = SOEFConnection(
        configuration=configuration, data_dir=data_dir, identity=identity
    )
    resources.add_connection(soef_connection)

    # create the AEA
    my_aea = AEA(
        identity,
        wallet,
        resources,
        data_dir,
        default_connection=default_connection,
        default_routing=default_routing,
    )
    # Add the error and weather_client skills
    error_skill = Skill.from_dir(
        os.path.join(ROOT_DIR, "packages", "fetchai", "skills", "error"),
        agent_context=my_aea.context,
    )
    weather_skill = Skill.from_dir(
        os.path.join(ROOT_DIR, "packages", "fetchai", "skills", "weather_client"),
        agent_context=my_aea.context,
    )

    strategy = cast(Strategy, weather_skill.models.get("strategy"))
    strategy._is_ledger_tx = False

    for skill in [error_skill, weather_skill]:
        resources.add_skill(skill)

    # Run the AEA
    try:
        logger.info("STARTING AEA NOW!")
        my_aea.start()
    except KeyboardInterrupt:
        logger.info("STOPPING AEA NOW!")
        my_aea.stop()
Пример #9
0
def run():
    # Create a private key
    create_private_key(FetchAICrypto.identifier)

    # Set up the wallet, identity and (empty) resources
    wallet = Wallet({FetchAICrypto.identifier: FETCHAI_PRIVATE_KEY_FILE})
    identity = Identity("my_aea",
                        address=wallet.addresses.get(FetchAICrypto.identifier))
    resources = Resources()

    # specify the default routing for some protocols
    default_routing = {
        PublicId.from_str("fetchai/ledger_api:0.1.0"):
        LedgerConnection.connection_id
    }
    default_connection = OEFConnection.connection_id

    # create the AEA
    my_aea = AEA(
        identity,
        wallet,
        resources,
        default_connection=default_connection,
        default_routing=default_routing,
    )

    # Add the default protocol (which is part of the AEA distribution)
    default_protocol = Protocol.from_dir(
        os.path.join(AEA_DIR, "protocols", "default"))
    resources.add_protocol(default_protocol)

    # Add the signing protocol (which is part of the AEA distribution)
    signing_protocol = Protocol.from_dir(
        os.path.join(AEA_DIR, "protocols", "signing"))
    resources.add_protocol(signing_protocol)

    # Add the ledger_api protocol
    ledger_api_protocol = Protocol.from_dir(
        os.path.join(
            os.getcwd(),
            "packages",
            "fetchai",
            "protocols",
            "ledger_api",
        ))
    resources.add_protocol(ledger_api_protocol)

    # Add the oef_search protocol
    oef_protocol = Protocol.from_dir(
        os.path.join(
            os.getcwd(),
            "packages",
            "fetchai",
            "protocols",
            "oef_search",
        ))
    resources.add_protocol(oef_protocol)

    # Add the fipa protocol
    fipa_protocol = Protocol.from_dir(
        os.path.join(
            os.getcwd(),
            "packages",
            "fetchai",
            "protocols",
            "fipa",
        ))
    resources.add_protocol(fipa_protocol)

    # Add the LedgerAPI connection
    configuration = ConnectionConfig(
        connection_id=LedgerConnection.connection_id)
    ledger_api_connection = LedgerConnection(configuration=configuration,
                                             identity=identity)
    resources.add_connection(ledger_api_connection)

    # Add the OEF connection
    configuration = ConnectionConfig(addr=HOST,
                                     port=PORT,
                                     connection_id=OEFConnection.connection_id)
    oef_connection = OEFConnection(configuration=configuration,
                                   identity=identity)
    resources.add_connection(oef_connection)

    # Add the error and weather_client skills
    error_skill = Skill.from_dir(os.path.join(AEA_DIR, "skills", "error"),
                                 agent_context=my_aea.context)
    weather_skill = Skill.from_dir(
        os.path.join(ROOT_DIR, "packages", "fetchai", "skills",
                     "weather_client"),
        agent_context=my_aea.context,
    )

    strategy = cast(Strategy, weather_skill.models.get("strategy"))
    strategy._is_ledger_tx = False

    for skill in [error_skill, weather_skill]:
        resources.add_skill(skill)

    # Run the AEA
    try:
        logger.info("STARTING AEA NOW!")
        my_aea.start()
    except KeyboardInterrupt:
        logger.info("STOPPING AEA NOW!")
        my_aea.stop()