Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 10 additions & 0 deletions python/src/uagents/agent.py
Original file line number Diff line number Diff line change
Expand Up @@ -637,6 +637,16 @@ def identifier(self) -> str:
"""
return self._prefix + "://" + self._identity.address

@property
def identity(self) -> Identity:
"""
Get the identity of the agent.

Returns:
Identity: The agent's identity.
"""
return self._identity

@property
def wallet(self) -> LocalWallet:
"""
Expand Down
5 changes: 4 additions & 1 deletion python/src/uagents/experimental/quota/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,7 @@ async def message_handler(ctx: Context, sender: str, msg: Message):

from pydantic import BaseModel
from uagents_core.models import ErrorMessage
from uagents_core.protocol import ProtocolSpecification

from uagents import Context, Model, Protocol
from uagents.storage import StorageAPI
Expand Down Expand Up @@ -108,6 +109,8 @@ def __init__(
storage_reference: StorageAPI,
name: str | None = None,
version: str | None = None,
spec: ProtocolSpecification | None = None,
role: str | None = None,
default_rate_limit: RateLimit | None = None,
default_acl: AccessControlList | None = None,
):
Expand All @@ -121,7 +124,7 @@ def __init__(
default_rate_limit (RateLimit | None): The default rate limit. Defaults to None.
default_acl (AccessControlList | None): The access control list. Defaults to None.
"""
super().__init__(name=name, version=version)
super().__init__(name=name, version=version, spec=spec, role=role)
self.storage_ref = storage_reference
self.default_rate_limit = default_rate_limit
self.default_acl = default_acl
Expand Down
116 changes: 116 additions & 0 deletions python/src/uagents/experimental/subscription/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,116 @@
"""
This Protocol class provides a basic example to support subscriptions.

If a requesting agent is on the free tier, it will be rate-limited according
to the specification given for the QuotaProtocol. If the agent is on a paid
tier (PLUS or PRO), it will not be rate-limited and can make requests
without restrictions.

Usage examples:

```python
from uagents.experimental.subscription import SubscribableProtocol

protocol_spec = ProtocolSpecification(...) # Import or create any protocol specification

# Initialize the SubscribableProtocol instance
subs_protocol = SubscribableProtocol(
storage_reference=agent.storage,
identity=agent.identity,
agentverse=agent.agentverse,
spec=protocol_spec,
# default_rate_limit=RateLimit(window_size_minutes=1, max_requests=3), # Optional
)

# Subscription and rate limiting does not apply to this message handler
@subs_protocol.on_message(ExampleMessage1)
async def handle(ctx: Context, sender: str, msg: ExampleMessage1):
...

# This message handler is rate limited with custom window size and request limit
# that will be bypassed if the agent is on a paid tier
@subs_protocol.on_message(
ExampleMessage2,
rate_limit=RateLimit(window_size_minutes=1, max_requests=3),
)
async def handle(ctx: Context, sender: str, msg: ExampleMessage2):
...
"""

from uagents_core.protocol import ProtocolSpecification
from uagents_core.utils.subscriptions import TierType, get_subscription_tier

from uagents.config import AgentverseConfig
from uagents.crypto import Identity
from uagents.experimental.quota import AccessControlList, QuotaProtocol, RateLimit
from uagents.storage import StorageAPI


class SubscribableProtocol(QuotaProtocol):
def __init__(
self,
storage_reference: StorageAPI,
identity: Identity,
agentverse: AgentverseConfig,
name: str | None = None,
version: str | None = None,
spec: ProtocolSpecification | None = None,
role: str | None = None,
default_rate_limit: RateLimit | None = None,
default_acl: AccessControlList | None = None,
):
"""
Initialize a SubscribableProtocol instance.

Args:
storage_reference (StorageAPI): The storage reference to use for rate limiting.
identity (Identity): The identity of the agent supporting subscriptions.
agentverse (AgentverseConfig): The agentverse configuration.
name (str | None): The name of the protocol. Defaults to None.
version (str | None): The version of the protocol. Defaults to None.
default_rate_limit (RateLimit | None): The default rate limit. Defaults to None.
default_acl (AccessControlList | None): The access control list. Defaults to None.
"""
self._identity = identity
self._agentverse = agentverse
super().__init__(
name=name,
version=version,
spec=spec,
role=role,
storage_reference=storage_reference,
default_rate_limit=default_rate_limit,
default_acl=default_acl,
)

def add_request(
self,
agent_address: str,
function_name: str,
window_size_minutes: int,
max_requests: int,
) -> bool:
"""
If the agent is on a paid tier, do not apply rate limiting. If the agent is
on the free tier, apply the rate limiting as specified by the QuotaProtocol.

Args:
agent_address: The address of the agent making the request.
function_name: The name of the function being called.
window_size_minutes: The size of the time window in minutes for rate limiting.
max_requests: The maximum number of requests allowed in the time window.

Returns:
False if the agent is on the free tier and the maximum number of requests
has been exceeded, True otherwise.
"""
tier = get_subscription_tier(self._identity, agent_address, self._agentverse)
if tier in (TierType.PLUS, TierType.PRO):
Comment thread
Dacksus marked this conversation as resolved.
return True

return super().add_request(
agent_address=agent_address,
function_name=function_name,
window_size_minutes=window_size_minutes,
max_requests=max_requests,
)
56 changes: 56 additions & 0 deletions python/tests/examples/34-subs/main.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
from datetime import datetime, timezone
from uuid import uuid4

from uagents_core.contrib.protocols.chat import (
ChatAcknowledgement,
ChatMessage,
TextContent,
chat_protocol_spec,
)

from uagents import Agent, Bureau, Context
from uagents.experimental.subscription import RateLimit, SubscribableProtocol

subscriber = Agent(name="Subscriber")
service_provider = Agent(name="ServiceProvider")


subs_chat_proto = SubscribableProtocol(
storage_reference=service_provider.storage,
identity=service_provider.identity,
agentverse=service_provider.agentverse,
spec=chat_protocol_spec,
default_rate_limit=RateLimit(window_size_minutes=60, max_requests=6),
)


@subs_chat_proto.on_message(ChatMessage)
async def handle_message(ctx: Context, sender: str, msg: ChatMessage):
ctx.logger.info(f"Received request request from {sender}")


@subs_chat_proto.on_message(ChatAcknowledgement)
async def handle_acknowledgement(ctx: Context, sender: str, msg: ChatAcknowledgement):
pass


service_provider.include(subs_chat_proto)


@subscriber.on_interval(2)
async def request_service(ctx: Context):
await ctx.send(
service_provider.address,
ChatMessage(
timestamp=datetime.now(timezone.utc),
msg_id=uuid4(),
content=[TextContent(type="text", text="Hello from subscriber!")],
),
)


bureau = Bureau(agents=[subscriber, service_provider])


if __name__ == "__main__":
bureau.run()