Пример #1
0
def test_agent_logger_adapter():
    """Test the agent logger adapter."""
    logger = logging.getLogger("some.logger")
    logger = AgentLoggerAdapter(logger, agent_name="some_agent")
    with patch.object(logger.logger, "log") as mock_logger:
        logger.debug("Some log message.")
        mock_logger.assert_any_call(logging.DEBUG,
                                    "[some_agent] Some log message.")
Пример #2
0
 def _setup_loggers(self):
     """Set up logger with agent name."""
     for element in [
             self.main_loop,
             self.multiplexer,
             self.task_manager,
             self.resources.component_registry,
             self.resources.behaviour_registry,
             self.resources.handler_registry,
             self.resources.model_registry,
     ]:
         element.logger = AgentLoggerAdapter(element.logger,
                                             agent_name=self._identity.name)
Пример #3
0
    def from_config(
        cls, configuration: SkillConfig, agent_context: AgentContext, **kwargs
    ) -> "Skill":
        """
        Load the skill from configuration.

        :param configuration: a skill configuration. Must be associated with a directory.
        :param agent_context: the agent context.
        :return: the skill.
        """

        if configuration.directory is None:  # pragma: nocover
            raise ValueError("Configuration must be associated with a directory.")

        # we put the initialization here because some skill components
        # might need some info from the skill
        # (e.g. see https://github.com/fetchai/agents-aea/issues/1095)
        skill_context = SkillContext()
        skill_context.set_agent_context(agent_context)
        logger_name = f"aea.packages.{configuration.author}.skills.{configuration.name}"
        logger_name = _get_aea_logger_name_prefix(logger_name, agent_context.agent_name)
        _logger = AgentLoggerAdapter(
            logging.getLogger(logger_name), agent_context.agent_name
        )
        skill_context.logger = cast(Logger, _logger)

        skill = Skill(configuration, skill_context, **kwargs)

        directory = configuration.directory
        load_aea_package(configuration)
        handlers_by_id = dict(configuration.handlers.read_all())
        handlers = Handler.parse_module(
            str(directory / "handlers.py"), handlers_by_id, skill_context
        )

        behaviours_by_id = dict(configuration.behaviours.read_all())
        behaviours = Behaviour.parse_module(
            str(directory / "behaviours.py"), behaviours_by_id, skill_context,
        )

        models_by_id = dict(configuration.models.read_all())
        model_instances = Model.parse_module(
            str(directory), models_by_id, skill_context
        )

        skill.handlers.update(handlers)
        skill.behaviours.update(behaviours)
        skill.models.update(model_instances)

        return skill
Пример #4
0
def make_logger(
    configuration: ComponentConfiguration, agent_name: str,
) -> Optional[logging.Logger]:
    """
    Make the logger for a component.

    :param configuration: the component configuration
    :param agent_name: the agent name
    :return: the logger.
    """
    if configuration.component_type == ComponentType.SKILL:
        # skip because skill object already have their own logger from the skill context.
        return None
    logger_name = f"aea.packages.{configuration.author}.{configuration.component_type.to_plural()}.{configuration.name}"
    _logger = AgentLoggerAdapter(logging.getLogger(logger_name), agent_name)
    return cast(logging.Logger, _logger)
Пример #5
0
 def _setup_loggers(self) -> None:
     """Set up logger with agent name."""
     for element in [
             self.runtime.agent_loop,
             self.runtime.multiplexer,
             self.runtime.task_manager,
             self.resources.component_registry,
             self.resources.behaviour_registry,
             self.resources.handler_registry,
             self.resources.model_registry,
     ]:
         element = cast(WithLogger, element)
         element.logger = cast(
             Logger,
             AgentLoggerAdapter(element.logger,
                                agent_name=self._identity.name),
         )
Пример #6
0
    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()
Пример #7
0
    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()
Пример #8
0
    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,
        )
        aea_logger = AgentLoggerAdapter(
            logger=logging.getLogger(__name__), agent_name=identity.name
        )
        WithLogger.__init__(self, logger=cast(logging.Logger, aea_logger))

        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()