Exemple #1
0
    def __init__(
        self,
        identity: Identity,
        connections: List[Connection],
        loop: Optional[AbstractEventLoop] = None,
        period: float = 1.0,
        loop_mode: Optional[str] = None,
        runtime_mode: Optional[str] = None,
        logger: Logger = _default_logger,
    ) -> 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 period: period to call agent's act
        :param loop_mode: loop_mode to choose agent run loop.
        :param runtime_mode: runtime mode to up agent.

        :return: None
        """
        WithLogger.__init__(self, logger=logger)
        self._connections = connections
        self._identity = identity
        self._period = period
        self._tick = 0
        self._runtime_mode = runtime_mode or self.DEFAULT_RUNTIME
        runtime_cls = self._get_runtime_class()
        self._runtime: BaseRuntime = runtime_cls(agent=self,
                                                 loop_mode=loop_mode,
                                                 loop=loop)

        self._inbox = InBox(self.runtime.multiplexer)
        self._outbox = OutBox(self.runtime.multiplexer)
Exemple #2
0
    def __init__(
        self,
        agent: AbstractAgent,
        loop_mode: Optional[str] = None,
        loop: Optional[AbstractEventLoop] = None,
        threaded: bool = False,
    ) -> None:
        """
        Init runtime.

        :param agent: Agent to run.
        :param loop_mode: agent main loop mode.
        :param loop: optional event loop. if not provided a new one will be created.
        :return: None
        """
        Runnable.__init__(self, threaded=threaded, loop=loop if not threaded else None)
        logger = get_logger(__name__, agent.name)
        WithLogger.__init__(self, logger=logger)
        self._agent: AbstractAgent = agent
        self._state: AsyncState = AsyncState(RuntimeStates.stopped, RuntimeStates)
        self._state.add_callback(self._log_runtime_state)

        self._multiplexer: AsyncMultiplexer = self._get_multiplexer_instance()
        self._task_manager = TaskManager()
        self._decision_maker: Optional[DecisionMaker] = None

        self._loop_mode = loop_mode or self.DEFAULT_RUN_LOOP
        self.main_loop: BaseAgentLoop = self._get_main_loop_instance(self._loop_mode)
Exemple #3
0
    def __init__(self, resources: Resources,
                 decision_maker_out_queue: AsyncFriendlyQueue) -> None:
        """
        Instantiate the filter.

        :param resources: the resources
        :param decision_maker_out_queue: the decision maker queue
        """
        logger = get_logger(__name__, resources.agent_name)
        WithLogger.__init__(self, logger=logger)
        self._resources = resources
        self._decision_maker_out_queue = decision_maker_out_queue
Exemple #4
0
    def __init__(
        self, agent: "Agent", loop: Optional[AbstractEventLoop] = None
    ) -> None:
        """Init loop.

        :params agent: Agent or AEA to run.
        :params loop: optional asyncio event loop. if not specified a new loop will be created.
        """
        WithLogger.__init__(self, logger)
        self._agent: "Agent" = agent
        self.set_loop(ensure_loop(loop))
        self._tasks: List[asyncio.Task] = []
        self._state: AsyncState = AsyncState()
        self._exceptions: List[Exception] = []
Exemple #5
0
    def __init__(
        self,
        configuration: Optional[ComponentConfiguration] = None,
        is_vendor: bool = False,
        **kwargs: Any,
    ) -> None:
        """
        Initialize a package.

        :param configuration: the package configuration.
        :param is_vendor: whether the package is vendorized.
        """
        WithLogger.__init__(self, **kwargs)
        self._configuration = configuration
        self._directory = None  # type: Optional[Path]
        self._is_vendor = is_vendor
Exemple #6
0
    def __init__(self, identity: Identity, wallet: Wallet, **kwargs):
        """
        Initialize the decision maker handler.

        :param identity: the identity
        :param wallet: the wallet
        :param logger: the logger
        :param kwargs: the key word arguments
        """
        logger = get_logger(__name__, identity.name)
        WithLogger.__init__(self, logger=logger)
        self._identity = identity
        self._wallet = wallet
        self._context = SimpleNamespace(**kwargs)
        self._message_out_queue = AsyncFriendlyQueue(
        )  # type: AsyncFriendlyQueue
Exemple #7
0
    def __init__(self, nb_workers: int = 1, is_lazy_pool_start: bool = True):
        """
        Initialize the task manager.

        :param nb_workers: the number of worker processes.
        :param is_lazy_pool_start: option to postpone pool creation till the first enqueue_task called.
        """
        WithLogger.__init__(self, logger)
        self._nb_workers = nb_workers
        self._is_lazy_pool_start = is_lazy_pool_start
        self._pool = None  # type: Optional[Pool]
        self._stopped = True
        self._lock = threading.Lock()

        self._task_enqueued_counter = 0
        self._results_by_task_id = {}  # type: Dict[int, Any]
Exemple #8
0
    def __init__(self,
                 configuration: Optional[ComponentConfiguration] = None,
                 is_vendor: bool = False,
                 **kwargs):
        """
        Initialize a package.

        :param configuration: the package configuration.
        :param is_vendor: whether the package is vendorized.
        """
        WithLogger.__init__(self, **kwargs)
        self._configuration = configuration
        self._directory = None  # type: Optional[Path]
        self._is_vendor = is_vendor

        # mapping from import path to module object
        # the keys are dotted paths of Python modules.
        self.importpath_to_module = {}  # type: Dict[str, types.ModuleType]
Exemple #9
0
    def __init__(
        self,
        agent: AbstractAgent,
        loop: Optional[AbstractEventLoop] = None,
        threaded: bool = False,
    ) -> None:
        """Init loop.

        :param agent: Agent or AEA to run.
        :param loop: optional asyncio event loop. if not specified a new loop will be created.
        """
        logger = get_logger(__name__, agent.name)
        WithLogger.__init__(self, logger)
        Runnable.__init__(self, loop=loop, threaded=threaded)

        self._agent: AbstractAgent = agent
        self._tasks: List[asyncio.Task] = []
        self._state: AsyncState = AsyncState(AgentLoopStates.initial)
        self._exceptions: List[Exception] = []
Exemple #10
0
    def __init__(
        self,
        decision_maker_handler: DecisionMakerHandler,
    ):
        """
        Initialize the decision maker.

        :param agent_name: the agent name
        :param decision_maker_handler: the decision maker handler
        """
        WithLogger.__init__(self, logger=decision_maker_handler.logger)
        self._agent_name = decision_maker_handler.identity.name
        self._queue_access_code = uuid4().hex
        self._message_in_queue = ProtectedQueue(
            self._queue_access_code)  # type: ProtectedQueue
        self._decision_maker_handler = decision_maker_handler
        self._thread = None  # type: Optional[Thread]
        self._lock = threading.Lock()
        self._message_out_queue = decision_maker_handler.message_out_queue
        self._stopped = True
Exemple #11
0
    def __init__(
        self,
        connections: Optional[Sequence[Connection]] = None,
        default_connection_index: int = 0,
        loop: Optional[AbstractEventLoop] = None,
        exception_policy: ExceptionPolicyEnum = ExceptionPolicyEnum.propagate,
        threaded: bool = False,
        agent_name: str = "standalone",
    ):
        """
        Initialize the connection multiplexer.

        :param connections: a sequence of connections.
        :param default_connection_index: the index of the connection to use as default.
            This information is used for envelopes which don't specify any routing context.
            If connections is None, this parameter is ignored.
        :param loop: the event loop to run the multiplexer. If None, a new event loop is created.
        :param agent_name: the name of the agent that owns the multiplexer, for logging purposes.
        """
        self._exception_policy: ExceptionPolicyEnum = exception_policy
        logger = get_logger(__name__, agent_name)
        WithLogger.__init__(self, logger=logger)
        Runnable.__init__(self, loop=loop, threaded=threaded)
        self._connections: List[Connection] = []
        self._id_to_connection: Dict[PublicId, Connection] = {}
        self._default_connection: Optional[Connection] = None
        self._initialize_connections_if_any(connections,
                                            default_connection_index)

        self._connection_status = MultiplexerStatus()

        self._in_queue = AsyncFriendlyQueue()  # type: AsyncFriendlyQueue
        self._out_queue = None  # type: Optional[asyncio.Queue]

        self._recv_loop_task = None  # type: Optional[asyncio.Task]
        self._send_loop_task = None  # type: Optional[asyncio.Task]
        self._default_routing = {}  # type: Dict[PublicId, PublicId]
        self._loop: asyncio.AbstractEventLoop = loop if loop is not None else asyncio.new_event_loop(
        )
        self._lock: asyncio.Lock = asyncio.Lock(loop=self._loop)
        self.set_loop(self._loop)
Exemple #12
0
    def __init__(
        self,
        identity: Identity,
        connections: List[Connection],
        loop: Optional[AbstractEventLoop] = None,
        period: float = 1.0,
        loop_mode: Optional[str] = None,
        runtime_mode: Optional[str] = None,
        storage_uri: Optional[str] = None,
        logger: Logger = _default_logger,
    ) -> 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 period: period to call agent's act
        :param loop_mode: loop_mode to choose agent run loop.
        :param runtime_mode: runtime mode to up agent.
        :param storage_uri: optional uri to set generic storage

        :return: None
        """
        WithLogger.__init__(self, logger=logger)
        self._identity = identity
        self._period = period
        self._tick = 0
        self._runtime_mode = runtime_mode or self.DEFAULT_RUNTIME
        self._storage_uri = storage_uri

        runtime_class = self._get_runtime_class()

        self._set_runtime_and_mail_boxes(
            runtime_class=runtime_class,
            loop_mode=loop_mode,
            loop=loop,
            multiplexer_options={"connections": connections},
        )
Exemple #13
0
    def __init__(
        self,
        connections: Optional[Sequence[Connection]] = None,
        default_connection_index: int = 0,
        loop: Optional[AbstractEventLoop] = None,
        exception_policy: ExceptionPolicyEnum = ExceptionPolicyEnum.propagate,
        threaded: bool = False,
        agent_name: str = "standalone",
        default_routing: Optional[Dict[PublicId, PublicId]] = None,
        default_connection: Optional[PublicId] = None,
        protocols: Optional[List[Union[Protocol, Message]]] = None,
    ) -> None:
        """
        Initialize the connection multiplexer.

        :param connections: a sequence of connections.
        :param default_connection_index: the index of the connection to use as default.
            This information is used for envelopes which don't specify any routing context.
            If connections is None, this parameter is ignored.
        :param loop: the event loop to run the multiplexer. If None, a new event loop is created.
        :param agent_name: the name of the agent that owns the multiplexer, for logging purposes.
        """
        self._exception_policy: ExceptionPolicyEnum = exception_policy
        logger = get_logger(__name__, agent_name)
        WithLogger.__init__(self, logger=logger)
        Runnable.__init__(self, loop=loop, threaded=threaded)

        self._connections: List[Connection] = []
        self._id_to_connection: Dict[PublicId, Connection] = {}
        self._default_connection: Optional[Connection] = None

        connections = connections or []
        if not default_connection and connections:
            enforce(
                len(connections) - 1 >= default_connection_index,
                "default_connection_index os out of connections range!",
            )
            default_connection = connections[
                default_connection_index].connection_id

        if default_connection:
            enforce(
                bool([
                    i.connection_id.same_prefix(default_connection)
                    for i in connections
                ]),
                f"Default connection {default_connection} does not present in connections list!",
            )

        self._default_routing = {}  # type: Dict[PublicId, PublicId]

        self._setup(connections or [], default_routing, default_connection)

        self._connection_status = MultiplexerStatus()
        self._specification_id_to_protocol_id = {
            p.protocol_specification_id: p.protocol_id
            for p in protocols or []
        }

        self._in_queue = AsyncFriendlyQueue()  # type: AsyncFriendlyQueue
        self._out_queue = None  # type: Optional[asyncio.Queue]

        self._recv_loop_task = None  # type: Optional[asyncio.Task]
        self._send_loop_task = None  # type: Optional[asyncio.Task]

        self._loop: asyncio.AbstractEventLoop = loop if loop is not None else asyncio.new_event_loop(
        )
        self._lock: asyncio.Lock = asyncio.Lock(loop=self._loop)
        self.set_loop(self._loop)
Exemple #14
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()