def test_agent_context(): """Test the agent context.""" agent_name = "name" address = "address" addresses = {FETCHAI: address} identity = Identity(agent_name, addresses) connection_status = "connection_status_stub" outbox = "outbox_stub" decision_maker_message_queue = "decision_maker_message_queue_stub" decision_maker_handler_context = "decision_maker_handler_context_stub" task_manager = "task_manager_stub" default_connection = "default_connection_stub" default_routing = "default_routing_stub" search_service_address = "search_service_address_stub" decision_maker_address = "decision_maker_address_stub" value = "some_value" kwargs = {"some_key": value} default_ledger_id = "fetchai" currency_denominations = {} data_dir = os.getcwd() def storage_callable_(): pass ac = AgentContext( identity=identity, connection_status=connection_status, outbox=outbox, decision_maker_message_queue=decision_maker_message_queue, decision_maker_handler_context=decision_maker_handler_context, task_manager=task_manager, default_ledger_id=default_ledger_id, currency_denominations=currency_denominations, default_connection=default_connection, default_routing=default_routing, search_service_address=search_service_address, decision_maker_address=decision_maker_address, storage_callable=storage_callable_, data_dir=data_dir, **kwargs ) assert ac.data_dir == data_dir assert ac.shared_state == {} assert ac.identity == identity assert ac.agent_name == identity.name assert ac.address == identity.address assert ac.addresses == identity.addresses assert ac.connection_status == connection_status assert ac.outbox == outbox assert ac.decision_maker_message_queue == decision_maker_message_queue assert ac.decision_maker_handler_context == decision_maker_handler_context assert ac.task_manager == task_manager assert ac.default_ledger_id == default_ledger_id assert ac.currency_denominations == currency_denominations assert ac.default_connection == default_connection assert ac.default_routing == default_routing assert ac.search_service_address == search_service_address assert ac.namespace.some_key == value assert ac.decision_maker_address == decision_maker_address assert ac.storage == storage_callable_()
def setup(cls) -> None: """Set up the skill test case.""" identity = Identity("test_agent_name", "test_agent_address") cls._multiplexer = AsyncMultiplexer() cls._multiplexer._out_queue = ( # pylint: disable=protected-access asyncio.Queue() ) cls._outbox = OutBox(cast(Multiplexer, cls._multiplexer)) agent_context = AgentContext( identity=identity, connection_status=cls._multiplexer.connection_status, outbox=cls._outbox, decision_maker_message_queue=Queue(), decision_maker_handler_context=SimpleNamespace(), task_manager=TaskManager(), default_ledger_id=identity.default_address_key, currency_denominations=DEFAULT_CURRENCY_DENOMINATIONS, default_connection=None, default_routing={}, search_service_address="dummy_search_service_address", decision_maker_address="dummy_decision_maker_address", ) cls._skill = Skill.from_dir(str(cls.path_to_skill), agent_context)
def setup(cls, **kwargs: Any) -> None: """Set up the skill test case.""" identity = Identity("test_agent_name", "test_agent_address") cls._multiplexer = AsyncMultiplexer() cls._multiplexer._out_queue = ( # pylint: disable=protected-access asyncio.Queue() ) cls._outbox = OutBox(cast(Multiplexer, cls._multiplexer)) _shared_state = cast(Dict[str, Any], kwargs.pop("shared_state", dict())) _skill_config_overrides = cast( Dict[str, Any], kwargs.pop("config_overrides", dict()) ) agent_context = AgentContext( identity=identity, connection_status=cls._multiplexer.connection_status, outbox=cls._outbox, decision_maker_message_queue=Queue(), decision_maker_handler_context=SimpleNamespace(), task_manager=TaskManager(), default_ledger_id=identity.default_address_key, currency_denominations=DEFAULT_CURRENCY_DENOMINATIONS, default_connection=None, default_routing={}, search_service_address="dummy_search_service_address", decision_maker_address="dummy_decision_maker_address", data_dir=os.getcwd(), ) # This enables pre-populating the 'shared_state' prior to loading the skill if _shared_state != dict(): for key, value in _shared_state.items(): agent_context.shared_state[key] = value skill_configuration_file_path: Path = Path(cls.path_to_skill, "skill.yaml") loader = ConfigLoaders.from_package_type(PackageType.SKILL) with open_file(skill_configuration_file_path) as fp: skill_config: SkillConfig = loader.load(fp) # This enables overriding the skill's config prior to loading if _skill_config_overrides != {}: skill_config.update(_skill_config_overrides) skill_config.directory = cls.path_to_skill cls._skill = Skill.from_config(skill_config, agent_context)
def __init__( self, identity: Identity, connections: List[Connection], wallet: Wallet, ledger_apis: LedgerApis, resources: Resources, loop: Optional[AbstractEventLoop] = None, timeout: float = 0.0, is_debug: bool = False, is_programmatic: bool = True, max_reactions: int = 20, ) -> None: """ Instantiate the agent. :param identity: the identity of the agent :param connections: the list of connections of the agent. :param loop: the event loop to run the connections. :param wallet: the wallet of the agent. :param ledger_apis: the ledger apis of the agent. :param resources: the resources of the agent. :param timeout: the time in (fractions of) seconds to time out an agent between act and react :param is_debug: if True, run the agent in debug mode. :param is_programmatic: if True, run the agent in programmatic mode (skips loading of resources from directory). :param max_reactions: the processing rate of messages per iteration. :return: None """ super().__init__( identity=identity, connections=connections, loop=loop, timeout=timeout, is_debug=is_debug, is_programmatic=is_programmatic, ) self.max_reactions = max_reactions self._task_manager = TaskManager() self._decision_maker = DecisionMaker( self.name, self.max_reactions, self.outbox, wallet, ledger_apis ) self._context = AgentContext( self.identity, ledger_apis, self.multiplexer.connection_status, self.outbox, self.decision_maker.message_in_queue, self.decision_maker.ownership_state, self.decision_maker.preferences, self.decision_maker.goal_pursuit_readiness, self.task_manager, ) self._resources = resources self._filter = Filter(self.resources, self.decision_maker.message_out_queue)
def __init__(self, name: str, connections: List[Connection], wallet: Wallet, ledger_apis: LedgerApis, resources: Resources, loop: Optional[AbstractEventLoop] = None, timeout: float = 0.0, debug: bool = False, max_reactions: int = 20) -> None: """ Instantiate the agent. :param name: the name of the agent :param connections: the list of connections of the agent. :param loop: the event loop to run the connections. :param wallet: the wallet of the agent. :param ledger_apis: the ledger apis of the agent. :param resources: the resources of the agent. :param timeout: the time in (fractions of) seconds to time out an agent between act and react :param debug: if True, run the agent in debug mode. :param max_reactions: the processing rate of messages per iteration. :return: None """ super().__init__(name=name, wallet=wallet, connections=connections, loop=loop, timeout=timeout, debug=debug) self.max_reactions = max_reactions self._decision_maker = DecisionMaker(self.name, self.max_reactions, self.outbox, self.wallet, ledger_apis) self._context = AgentContext( self.name, self.wallet.public_keys, self.wallet.addresses, ledger_apis, self.multiplexer.connection_status, self.outbox, self.decision_maker.message_in_queue, self.decision_maker.ownership_state, self.decision_maker.preferences, self.decision_maker.goal_pursuit_readiness) self._resources = resources self._filter = Filter(self.resources, self.decision_maker.message_out_queue)
def test_agent_context(): """Test the agent context.""" agent_name = "name" address = "address" addresses = {"fetchai": address} identity = Identity(agent_name, addresses) connection_status = "connection_status_stub" outbox = "outbox_stub" decision_maker_message_queue = "decision_maker_message_queue_stub" decision_maker_handler_context = "decision_maker_handler_context_stub" task_manager = "task_manager_stub" default_connection = "default_connection_stub" default_routing = "default_routing_stub" search_service_address = "search_service_address_stub" value = "some_value" kwargs = {"some_key": value} ac = AgentContext( identity=identity, connection_status=connection_status, outbox=outbox, decision_maker_message_queue=decision_maker_message_queue, decision_maker_handler_context=decision_maker_handler_context, task_manager=task_manager, default_connection=default_connection, default_routing=default_routing, search_service_address=search_service_address, **kwargs ) assert ac.shared_state == {} assert ac.identity == identity assert ac.agent_name == identity.name assert ac.address == identity.address assert ac.addresses == identity.addresses assert ac.connection_status == connection_status assert ac.outbox == outbox assert ac.decision_maker_message_queue == decision_maker_message_queue assert ac.decision_maker_handler_context == decision_maker_handler_context assert ac.task_manager == task_manager assert ac.default_connection == default_connection assert ac.default_routing == default_routing assert ac.search_service_address == search_service_address assert ac.namespace.some_key == value
def __init__(self, name: str, mailbox: MailBox, private_key_pem_path: Optional[str] = None, timeout: float = 0.0, debug: bool = False, max_reactions: int = 20, directory: str = '') -> None: """ Instantiate the agent. :param name: the name of the agent :param mailbox: the mailbox of the agent. :param private_key_pem_path: the path to the private key of the agent. :param timeout: the time in (fractions of) seconds to time out an agent between act and react :param debug: if True, run the agent in debug mode. :param max_reactions: the processing rate of messages per iteration. :param directory: the path to the agent's resource directory. | If None, we assume the directory is in the working directory of the interpreter. :return: None """ super().__init__(name=name, private_key_pem_path=private_key_pem_path, timeout=timeout, debug=debug) self.max_reactions = max_reactions self._directory = directory if directory else str(Path(".").absolute()) self.mailbox = mailbox self._decision_maker = DecisionMaker(self.max_reactions, self.outbox) self._context = AgentContext(self.name, self.crypto.public_key, self.outbox, self.decision_maker.message_queue, self.decision_maker.ownership_state, self.decision_maker.preferences, self.decision_maker.is_ready_to_pursuit_goals) self._resources = None # type: Optional[Resources]
def __init__( self, identity: Identity, wallet: Wallet, resources: Resources, loop: Optional[AbstractEventLoop] = None, timeout: float = 0.05, execution_timeout: float = 0, max_reactions: int = 20, decision_maker_handler_class: Type[ DecisionMakerHandler] = DefaultDecisionMakerHandler, skill_exception_policy: ExceptionPolicyEnum = ExceptionPolicyEnum. propagate, loop_mode: Optional[str] = None, runtime_mode: Optional[str] = None, default_connection: Optional[PublicId] = None, default_routing: Optional[Dict[PublicId, PublicId]] = None, connection_ids: Optional[Collection[PublicId]] = None, search_service_address: str = "fetchai/soef:*", **kwargs, ) -> None: """ Instantiate the agent. :param identity: the identity of the agent :param wallet: the wallet of the agent. :param resources: the resources (protocols and skills) of the agent. :param loop: the event loop to run the connections. :param timeout: the time in (fractions of) seconds to time out an agent between act and react :param exeution_timeout: amount of time to limit single act/handle to execute. :param max_reactions: the processing rate of envelopes per tick (i.e. single loop). :param decision_maker_handler_class: the class implementing the decision maker handler to be used. :param skill_exception_policy: the skill exception policy enum :param loop_mode: loop_mode to choose agent run loop. :param runtime_mode: runtime mode (async, threaded) to run AEA in. :param default_connection: public id to the default connection :param default_routing: dictionary for default routing. :param connection_ids: active connection ids. Default: consider all the ones in the resources. :param search_service_address: the address of the search service used. :param kwargs: keyword arguments to be attached in the agent context namespace. :return: None """ super().__init__( identity=identity, connections=[], loop=loop, timeout=timeout, loop_mode=loop_mode, runtime_mode=runtime_mode, ) self.max_reactions = max_reactions self._task_manager = TaskManager() decision_maker_handler = decision_maker_handler_class( identity=identity, wallet=wallet) self._decision_maker = DecisionMaker( decision_maker_handler=decision_maker_handler) self._context = AgentContext( self.identity, self.multiplexer.connection_status, self.outbox, self.decision_maker.message_in_queue, decision_maker_handler.context, self.task_manager, default_connection, default_routing if default_routing is not None else {}, search_service_address, **kwargs, ) self._execution_timeout = execution_timeout self._connection_ids = connection_ids self._resources = resources self._filter = Filter(self.resources, self.decision_maker.message_out_queue) self._skills_exception_policy = skill_exception_policy self._setup_loggers()
def __init__( self, identity: Identity, connections: List[Connection], wallet: Wallet, ledger_apis: LedgerApis, resources: Resources, loop: Optional[AbstractEventLoop] = None, timeout: float = 0.05, execution_timeout: float = 0, is_debug: bool = False, max_reactions: int = 20, decision_maker_handler_class: Type[ DecisionMakerHandler ] = DefaultDecisionMakerHandler, skill_exception_policy: ExceptionPolicyEnum = ExceptionPolicyEnum.propagate, loop_mode: Optional[str] = None, **kwargs, ) -> None: """ Instantiate the agent. :param identity: the identity of the agent :param connections: the list of connections of the agent. :param wallet: the wallet of the agent. :param ledger_apis: the APIs the agent will use to connect to ledgers. :param resources: the resources (protocols and skills) of the agent. :param loop: the event loop to run the connections. :param timeout: the time in (fractions of) seconds to time out an agent between act and react :param exeution_timeout: amount of time to limit single act/handle to execute. :param is_debug: if True, run the agent in debug mode (does not connect the multiplexer). :param max_reactions: the processing rate of envelopes per tick (i.e. single loop). :param decision_maker_handler_class: the class implementing the decision maker handler to be used. :param skill_exception_policy: the skill exception policy enum :param loop_mode: loop_mode to choose agent run loop. :param kwargs: keyword arguments to be attached in the agent context namespace. :return: None """ super().__init__( identity=identity, connections=connections, loop=loop, timeout=timeout, is_debug=is_debug, loop_mode=loop_mode, ) self.max_reactions = max_reactions self._task_manager = TaskManager() decision_maker_handler = decision_maker_handler_class( identity=identity, wallet=wallet, ledger_apis=ledger_apis ) self._decision_maker = DecisionMaker( decision_maker_handler=decision_maker_handler ) self._context = AgentContext( self.identity, ledger_apis, self.multiplexer.connection_status, self.outbox, self.decision_maker.message_in_queue, decision_maker_handler.context, self.task_manager, **kwargs, ) self._execution_timeout = execution_timeout self._resources = resources self._filter = Filter(self.resources, self.decision_maker.message_out_queue) self._skills_exception_policy = skill_exception_policy
def __init__( self, identity: Identity, wallet: Wallet, resources: Resources, loop: Optional[AbstractEventLoop] = None, period: float = 0.05, execution_timeout: float = 0, max_reactions: int = 20, decision_maker_handler_class: Optional[ Type[DecisionMakerHandler]] = None, skill_exception_policy: ExceptionPolicyEnum = ExceptionPolicyEnum. propagate, connection_exception_policy: ExceptionPolicyEnum = ExceptionPolicyEnum. propagate, loop_mode: Optional[str] = None, runtime_mode: Optional[str] = None, default_ledger: Optional[str] = None, currency_denominations: Optional[Dict[str, str]] = None, default_connection: Optional[PublicId] = None, default_routing: Optional[Dict[PublicId, PublicId]] = None, connection_ids: Optional[Collection[PublicId]] = None, search_service_address: str = DEFAULT_SEARCH_SERVICE_ADDRESS, **kwargs, ) -> None: """ Instantiate the agent. :param identity: the identity of the agent :param wallet: the wallet of the agent. :param resources: the resources (protocols and skills) of the agent. :param loop: the event loop to run the connections. :param period: period to call agent's act :param execution_timeout: amount of time to limit single act/handle to execute. :param max_reactions: the processing rate of envelopes per tick (i.e. single loop). :param decision_maker_handler_class: the class implementing the decision maker handler to be used. :param skill_exception_policy: the skill exception policy enum :param loop_mode: loop_mode to choose agent run loop. :param runtime_mode: runtime mode (async, threaded) to run AEA in. :param default_ledger: default ledger id :param currency_denominations: mapping from ledger id to currency denomination :param default_connection: public id to the default connection :param default_routing: dictionary for default routing. :param connection_ids: active connection ids. Default: consider all the ones in the resources. :param search_service_address: the address of the search service used. :param kwargs: keyword arguments to be attached in the agent context namespace. :return: None """ self._skills_exception_policy = skill_exception_policy self._connection_exception_policy = connection_exception_policy aea_logger = AgentLoggerAdapter( logger=get_logger(__name__, identity.name), agent_name=identity.name, ) super().__init__( identity=identity, connections=[], loop=loop, period=period, loop_mode=loop_mode, runtime_mode=runtime_mode, logger=cast(Logger, aea_logger), ) self.max_reactions = max_reactions if decision_maker_handler_class is None: from aea.decision_maker.default import ( # isort:skip # pylint: disable=import-outside-toplevel DecisionMakerHandler as DefaultDecisionMakerHandler, ) decision_maker_handler_class = DefaultDecisionMakerHandler decision_maker_handler = decision_maker_handler_class( identity=identity, wallet=wallet) self.runtime.set_decision_maker(decision_maker_handler) default_ledger_id = (default_ledger if default_ledger is not None else identity.default_address_key) currency_denominations = (currency_denominations if currency_denominations is not None else DEFAULT_CURRENCY_DENOMINATIONS) self._context = AgentContext( self.identity, self.runtime.multiplexer.connection_status, self.outbox, self.runtime.decision_maker.message_in_queue, decision_maker_handler.context, self.runtime.task_manager, default_ledger_id, currency_denominations, default_connection, default_routing if default_routing is not None else {}, search_service_address, decision_maker_handler.self_address, **kwargs, ) self._execution_timeout = execution_timeout self._connection_ids = connection_ids self._resources = resources self._filter = Filter(self.resources, self.runtime.decision_maker.message_out_queue) self._setup_loggers()
def __init__( self, identity: Identity, wallet: Wallet, resources: Resources, data_dir: str, loop: Optional[AbstractEventLoop] = None, period: float = 0.05, execution_timeout: float = 0, max_reactions: int = 20, error_handler_class: Optional[Type[AbstractErrorHandler]] = None, decision_maker_handler_class: Optional[ Type[DecisionMakerHandler]] = None, skill_exception_policy: ExceptionPolicyEnum = ExceptionPolicyEnum. propagate, connection_exception_policy: ExceptionPolicyEnum = ExceptionPolicyEnum. propagate, loop_mode: Optional[str] = None, runtime_mode: Optional[str] = None, default_ledger: Optional[str] = None, currency_denominations: Optional[Dict[str, str]] = None, default_connection: Optional[PublicId] = None, default_routing: Optional[Dict[PublicId, PublicId]] = None, connection_ids: Optional[Collection[PublicId]] = None, search_service_address: str = DEFAULT_SEARCH_SERVICE_ADDRESS, storage_uri: Optional[str] = None, **kwargs: Any, ) -> None: """ Instantiate the agent. :param identity: the identity of the agent :param wallet: the wallet of the agent. :param resources: the resources (protocols and skills) of the agent. :param data_dir: directory where to put local files. :param loop: the event loop to run the connections. :param period: period to call agent's act :param execution_timeout: amount of time to limit single act/handle to execute. :param max_reactions: the processing rate of envelopes per tick (i.e. single loop). :param decision_maker_handler_class: the class implementing the decision maker handler to be used. :param skill_exception_policy: the skill exception policy enum :param loop_mode: loop_mode to choose agent run loop. :param runtime_mode: runtime mode (async, threaded) to run AEA in. :param default_ledger: default ledger id :param currency_denominations: mapping from ledger id to currency denomination :param default_connection: public id to the default connection :param default_routing: dictionary for default routing. :param connection_ids: active connection ids. Default: consider all the ones in the resources. :param search_service_address: the address of the search service used. :param storage_uri: optional uri to set generic storage :param kwargs: keyword arguments to be attached in the agent context namespace. :return: None """ self._skills_exception_policy = skill_exception_policy self._connection_exception_policy = connection_exception_policy aea_logger = AgentLoggerAdapter( logger=get_logger(__name__, identity.name), agent_name=identity.name, ) self._resources = resources super().__init__( identity=identity, connections=[], loop=loop, period=period, loop_mode=loop_mode, runtime_mode=runtime_mode, storage_uri=storage_uri, logger=cast(Logger, aea_logger), ) default_routing = default_routing if default_routing is not None else {} connection_ids = connection_ids or [] connections = [ c for c in self.resources.get_all_connections() if (not connection_ids) or (c.connection_id in connection_ids) ] if not bool(self.resources.get_all_connections()): self.logger.warning( "Resource's connections list is empty! Instantiating AEA without connections..." ) elif bool(self.resources.get_all_connections() ) and not bool(connections): self.logger.warning( # pragma: nocover "No connection left after filtering! Instantiating AEA without connections..." ) self._set_runtime_and_mail_boxes( runtime_class=self._get_runtime_class(), loop_mode=loop_mode, loop=loop, multiplexer_options=dict( connections=connections, default_routing=default_routing, default_connection=default_connection, protocols=self.resources.get_all_protocols(), ), ) self.max_reactions = max_reactions if decision_maker_handler_class is None: from aea.decision_maker.default import ( # isort:skip # pylint: disable=import-outside-toplevel DecisionMakerHandler as DefaultDecisionMakerHandler, ) decision_maker_handler_class = DefaultDecisionMakerHandler decision_maker_handler = decision_maker_handler_class( identity=identity, wallet=wallet) self.runtime.set_decision_maker(decision_maker_handler) if error_handler_class is None: error_handler_class = DefaultErrorHandler self._error_handler_class = error_handler_class default_ledger_id = (default_ledger if default_ledger is not None else identity.default_address_key) currency_denominations = (currency_denominations if currency_denominations is not None else DEFAULT_CURRENCY_DENOMINATIONS) self._context = AgentContext( self.identity, self.runtime.multiplexer.connection_status, self.outbox, self.runtime.decision_maker.message_in_queue, decision_maker_handler.context, self.runtime.task_manager, default_ledger_id, currency_denominations, default_connection, default_routing, search_service_address, decision_maker_handler.self_address, data_dir, storage_callable=lambda: self.runtime.storage, build_dir=self.get_build_dir(), **kwargs, ) self._execution_timeout = execution_timeout self._filter = Filter(self.resources, self.runtime.decision_maker.message_out_queue) self._setup_loggers()