Skip to content

Commit

Permalink
feat: create functionality to decide for the bet's choice
Browse files Browse the repository at this point in the history
  • Loading branch information
Adamantios committed Jul 6, 2023
1 parent 196e463 commit 64ceb66
Show file tree
Hide file tree
Showing 10 changed files with 716 additions and 0 deletions.
5 changes: 5 additions & 0 deletions packages/valory/skills/decision_maker_abci/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
# DecisionMaker abci

## Description

This module contains the ABCI decision-making skill for an AEA.
25 changes: 25 additions & 0 deletions packages/valory/skills/decision_maker_abci/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
# -*- coding: utf-8 -*-
# ------------------------------------------------------------------------------
#
# Copyright 2023 Valory AG
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# ------------------------------------------------------------------------------

"""This module contains the decision maker skill for the trader."""

from aea.configurations.base import PublicId


PUBLIC_ID = PublicId.from_str("valory/decision_maker_abci:0.1.0")
124 changes: 124 additions & 0 deletions packages/valory/skills/decision_maker_abci/behaviours.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,124 @@
# -*- coding: utf-8 -*-
# ------------------------------------------------------------------------------
#
# Copyright 2023 Valory AG
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# ------------------------------------------------------------------------------

"""This module contains the behaviours for the 'decision_maker_abci' skill."""

from multiprocessing.pool import AsyncResult
from typing import Set, Type, cast, Any, Optional, Generator, Tuple

from packages.valory.skills.abstract_round_abci.base import BaseTxPayload
from packages.valory.skills.abstract_round_abci.behaviours import (
AbstractRoundBehaviour,
BaseBehaviour,
)
from packages.valory.skills.decision_maker_abci.models import DecisionMakerParams
from packages.valory.skills.decision_maker_abci.payloads import DecisionMakerPayload
from packages.valory.skills.decision_maker_abci.rounds import (
AgentDecisionMakerAbciApp,
DecisionMakerRound, SynchronizedData
)
from packages.valory.skills.decision_maker_abci.tasks import MechInteractionTask, MechInteractionResponse


class DecisionMakerBehaviour(BaseBehaviour):
"""A round in which the agents decide which answer they are going to choose for the next bet."""

matching_round = DecisionMakerRound

def __init__(self, **kwargs: Any) -> None:
"""Initialize Behaviour."""
super().__init__(**kwargs)
self._async_result: Optional[AsyncResult] = None

@property
def params(self) -> DecisionMakerParams:
"""Return the params."""
return cast(DecisionMakerParams, self.context.params)

@property
def synchronized_data(self) -> SynchronizedData:
"""Return the synchronized data."""
return cast(SynchronizedData, super().synchronized_data)

def setup(self) -> None:
"""Setup behaviour."""
mech_task = MechInteractionTask()
sampled_bet = self.synchronized_data.sampled_bet.title
task_kwargs = dict(
question=sampled_bet.title,
yes=sampled_bet.yes,
no=sampled_bet.no,
agent_id=self.params.mech_agent_id,
tool=self.params.mech_tool,
private_key_path=self.context.private_key_paths.read("ethereum")
)
task_id = self.context.task_manager.enqueue_task(
mech_task, kwargs=task_kwargs
)
self._async_result = self.context.task_manager.get_task_result(task_id)

def _get_decision(self) -> Generator[None, None, Optional[Tuple[bool, float]]]:
"""Get the vote and it's confidence."""
self._async_result = cast(AsyncResult, self._async_result)
if not self._async_result.ready():
self.context.logger.debug("The decision making task is not finished yet.")
yield from self.sleep(self.params.sleep_time)
return None

# Get the decision from the task.
mech_response = cast(MechInteractionResponse, self._async_result.get())
self.context.logger.info(
f"Decision has been received:\n{mech_response}"
)

if mech_response.prediction is None:
return False, 0

return mech_response.prediction.vote, mech_response.prediction.confidence

def finish_behaviour(self, payload: BaseTxPayload) -> Generator:
"""Finish the behaviour."""
with self.context.benchmark_tool.measure(self.behaviour_id).consensus():
yield from self.send_a2a_transaction(payload)
yield from self.wait_until_round_end()

self.set_done()

def async_act(self) -> Generator:
"""Do the action."""

with self.context.benchmark_tool.measure(self.behaviour_id).local():
decision = yield from self._get_decision()
if decision is None:
return

vote, confidence = decision
payload = DecisionMakerPayload(self.context.agent_address, vote, confidence)

yield from self.finish_behaviour(payload)


class AgentDecisionMakerRoundBehaviour(AbstractRoundBehaviour):
"""This behaviour manages the consensus stages for the decision making."""

initial_behaviour_cls = DecisionMakerBehaviour
abci_app_cls = AgentDecisionMakerAbciApp
behaviours: Set[Type[BaseBehaviour]] = {
DecisionMakerBehaviour, # type: ignore
}
91 changes: 91 additions & 0 deletions packages/valory/skills/decision_maker_abci/dialogues.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,91 @@
# -*- coding: utf-8 -*-
# ------------------------------------------------------------------------------
#
# Copyright 2023 Valory AG
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# ------------------------------------------------------------------------------

"""This module contains the classes required for dialogue management."""

from packages.valory.skills.abstract_round_abci.dialogues import (
AbciDialogue as BaseAbciDialogue,
)
from packages.valory.skills.abstract_round_abci.dialogues import (
AbciDialogues as BaseAbciDialogues,
)
from packages.valory.skills.abstract_round_abci.dialogues import (
ContractApiDialogue as BaseContractApiDialogue,
)
from packages.valory.skills.abstract_round_abci.dialogues import (
ContractApiDialogues as BaseContractApiDialogues,
)
from packages.valory.skills.abstract_round_abci.dialogues import (
HttpDialogue as BaseHttpDialogue,
)
from packages.valory.skills.abstract_round_abci.dialogues import (
HttpDialogues as BaseHttpDialogues,
)
from packages.valory.skills.abstract_round_abci.dialogues import (
IpfsDialogue as BaseIpfsDialogue,
)
from packages.valory.skills.abstract_round_abci.dialogues import (
IpfsDialogues as BaseIpfsDialogues,
)
from packages.valory.skills.abstract_round_abci.dialogues import (
LedgerApiDialogue as BaseLedgerApiDialogue,
)
from packages.valory.skills.abstract_round_abci.dialogues import (
LedgerApiDialogues as BaseLedgerApiDialogues,
)
from packages.valory.skills.abstract_round_abci.dialogues import (
SigningDialogue as BaseSigningDialogue,
)
from packages.valory.skills.abstract_round_abci.dialogues import (
SigningDialogues as BaseSigningDialogues,
)
from packages.valory.skills.abstract_round_abci.dialogues import (
TendermintDialogue as BaseTendermintDialogue,
)
from packages.valory.skills.abstract_round_abci.dialogues import (
TendermintDialogues as BaseTendermintDialogues,
)


AbciDialogue = BaseAbciDialogue
AbciDialogues = BaseAbciDialogues


HttpDialogue = BaseHttpDialogue
HttpDialogues = BaseHttpDialogues


SigningDialogue = BaseSigningDialogue
SigningDialogues = BaseSigningDialogues


LedgerApiDialogue = BaseLedgerApiDialogue
LedgerApiDialogues = BaseLedgerApiDialogues


ContractApiDialogue = BaseContractApiDialogue
ContractApiDialogues = BaseContractApiDialogues


TendermintDialogue = BaseTendermintDialogue
TendermintDialogues = BaseTendermintDialogues


IpfsDialogue = BaseIpfsDialogue
IpfsDialogues = BaseIpfsDialogues
51 changes: 51 additions & 0 deletions packages/valory/skills/decision_maker_abci/handlers.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
# -*- coding: utf-8 -*-
# ------------------------------------------------------------------------------
#
# Copyright 2023 Valory AG
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# ------------------------------------------------------------------------------

"""This module contains the handler for the 'decision_maker_abci' skill."""

from packages.valory.skills.abstract_round_abci.handlers import (
ABCIRoundHandler as BaseABCIRoundHandler,
)
from packages.valory.skills.abstract_round_abci.handlers import (
ContractApiHandler as BaseContractApiHandler,
)
from packages.valory.skills.abstract_round_abci.handlers import (
HttpHandler as BaseHttpHandler,
)
from packages.valory.skills.abstract_round_abci.handlers import (
IpfsHandler as BaseIpfsHandler,
)
from packages.valory.skills.abstract_round_abci.handlers import (
LedgerApiHandler as BaseLedgerApiHandler,
)
from packages.valory.skills.abstract_round_abci.handlers import (
SigningHandler as BaseSigningHandler,
)
from packages.valory.skills.abstract_round_abci.handlers import (
TendermintHandler as BaseTendermintHandler,
)


ABCIHandler = BaseABCIRoundHandler
HttpHandler = BaseHttpHandler
SigningHandler = BaseSigningHandler
LedgerApiHandler = BaseLedgerApiHandler
ContractApiHandler = BaseContractApiHandler
TendermintHandler = BaseTendermintHandler
IpfsHandler = BaseIpfsHandler
52 changes: 52 additions & 0 deletions packages/valory/skills/decision_maker_abci/models.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
# -*- coding: utf-8 -*-
# ------------------------------------------------------------------------------
#
# Copyright 2023 Valory AG
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# ------------------------------------------------------------------------------

"""This module contains the models for the skill."""

from typing import Any

from packages.valory.skills.abstract_round_abci.models import BaseParams
from packages.valory.skills.abstract_round_abci.models import (
BenchmarkTool as BaseBenchmarkTool,
)
from packages.valory.skills.abstract_round_abci.models import Requests as BaseRequests
from packages.valory.skills.abstract_round_abci.models import (
SharedState as BaseSharedState,
)
from packages.valory.skills.decision_maker_abci.rounds import AgentDecisionMakerAbciApp


Requests = BaseRequests
BenchmarkTool = BaseBenchmarkTool


class SharedState(BaseSharedState):
"""Keep the current shared state of the skill."""

abci_app_cls = AgentDecisionMakerAbciApp


class DecisionMakerParams(BaseParams):
"""Decision maker's parameters."""

def __init__(self, *args: Any, **kwargs: Any) -> None:
"""Initialize the parameters' object."""
self.mech_agent_id: int = self._ensure("mech_agent_id", kwargs, int)
self.mech_tool: int = self._ensure("mech_tool", kwargs, str)
super().__init__(*args, **kwargs)
32 changes: 32 additions & 0 deletions packages/valory/skills/decision_maker_abci/payloads.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
# -*- coding: utf-8 -*-
# ------------------------------------------------------------------------------
#
# Copyright 2023 Valory AG
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# ------------------------------------------------------------------------------

"""This module contains the transaction payloads for the decision maker."""

from dataclasses import dataclass

from packages.valory.skills.abstract_round_abci.base import BaseTxPayload


@dataclass(frozen=True)
class DecisionMakerPayload(BaseTxPayload):
"""Represents a transaction payload for the decision-making."""

vote: bool
confidence: float
Loading

0 comments on commit 64ceb66

Please sign in to comment.