-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathagents.py
More file actions
240 lines (188 loc) · 6.99 KB
/
agents.py
File metadata and controls
240 lines (188 loc) · 6.99 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
"""
Agent Identity and Reputation System
This module implements autonomous agents with reputation scores,
mock cryptographic signatures, and reputation decay mechanisms.
"""
import uuid
import hashlib
import time
from typing import Dict, List
from faker import Faker
class Agent:
"""
Represents an autonomous agent in the ASI Chain network.
Attributes:
agent_id (str): Unique identifier for the agent
name (str): Human-readable name
public_key (str): Mock public key (UUID-based)
private_key (str): Mock private key (UUID-based)
reputation (float): Current reputation score
creation_time (float): Timestamp when agent was created
transaction_history (List[Dict]): List of transactions
"""
def __init__(self, name: str = None, initial_reputation: float = 75.0):
"""
Initialize a new agent with mock keypair and reputation.
Args:
name: Optional name for the agent
initial_reputation: Starting reputation score (default: 75.0)
"""
self.agent_id = str(uuid.uuid4())
self.name = name or f"Agent-{self.agent_id[:8]}"
# Mock keypair (UUID-based)
self.public_key = str(uuid.uuid4())
self.private_key = str(uuid.uuid4())
# Reputation system
self.reputation = initial_reputation
self.creation_time = time.time()
self.transaction_history: List[Dict] = []
def sign_action(self, action: str) -> str:
"""
Create a mock signature for an action.
Args:
action: The action string to sign
Returns:
Mock signature (hash of agent_id + private_key + action)
"""
signature_string = f"{self.agent_id}:{self.private_key}:{action}"
signature = hashlib.sha256(signature_string.encode()).hexdigest()
return signature
def verify_signature(self, action: str, signature: str) -> bool:
"""
Verify a mock signature.
Args:
action: The action that was signed
signature: The signature to verify
Returns:
True if signature is valid, False otherwise
"""
expected_signature = self.sign_action(action)
return signature == expected_signature
def update_reputation(self, delta: float):
"""
Update agent's reputation score.
Args:
delta: Amount to change reputation (positive or negative)
"""
self.reputation += delta
# Keep reputation within reasonable bounds
self.reputation = max(0.0, min(100.0, self.reputation))
def apply_decay(self, decay_rate: float = 0.01, time_elapsed: float = 1.0):
"""
Apply exponential reputation decay over time.
Args:
decay_rate: Rate of decay per time unit (default: 0.01)
time_elapsed: Time units elapsed (default: 1.0)
"""
import math
decay_factor = math.exp(-decay_rate * time_elapsed)
self.reputation *= decay_factor
self.reputation = max(0.0, self.reputation)
def add_transaction(self, transaction: Dict):
"""
Add a transaction to the agent's history.
Args:
transaction: Dictionary containing transaction details
"""
self.transaction_history.append({
**transaction,
'timestamp': time.time()
})
def get_age(self) -> float:
"""
Get the age of the agent in seconds.
Returns:
Age in seconds since creation
"""
return time.time() - self.creation_time
def to_dict(self) -> Dict:
"""
Convert agent to dictionary representation.
Returns:
Dictionary with agent details
"""
return {
'agent_id': self.agent_id,
'name': self.name,
'public_key': self.public_key,
'reputation': round(self.reputation, 2),
'age': round(self.get_age(), 2),
'transaction_count': len(self.transaction_history)
}
def __repr__(self) -> str:
return f"Agent(id={self.agent_id[:8]}..., name={self.name}, reputation={self.reputation:.2f})"
def generate_agents(n: int = 10, seed: int = 42) -> List[Agent]:
"""
Generate a list of agents with random names and varied reputation.
Args:
n: Number of agents to generate
seed: Random seed for reproducibility
Returns:
List of Agent instances
"""
fake = Faker()
Faker.seed(seed)
import random
random.seed(seed)
agents = []
for _ in range(n):
name = fake.name()
# Varied initial reputation between 50 and 100
initial_rep = random.uniform(50.0, 100.0)
agent = Agent(name=name, initial_reputation=initial_rep)
agents.append(agent)
return agents
def calculate_reputation_metrics(agents: List[Agent]) -> Dict:
"""
Calculate aggregate reputation metrics for a group of agents.
Args:
agents: List of Agent instances
Returns:
Dictionary with reputation statistics
"""
if not agents:
return {
'total_agents': 0,
'average_reputation': 0.0,
'max_reputation': 0.0,
'min_reputation': 0.0,
'total_reputation': 0.0
}
reputations = [agent.reputation for agent in agents]
return {
'total_agents': len(agents),
'average_reputation': sum(reputations) / len(reputations),
'max_reputation': max(reputations),
'min_reputation': min(reputations),
'total_reputation': sum(reputations)
}
if __name__ == "__main__":
# Demo usage
print("=== ASI Chain Agent System Demo ===\n")
# Generate agents
agents = generate_agents(5)
print("Generated Agents:")
for agent in agents:
print(f" {agent}")
print("\n" + "="*50 + "\n")
# Test signing
test_agent = agents[0]
action = "transfer_100_tokens_to_agent_xyz"
signature = test_agent.sign_action(action)
print(f"Agent: {test_agent.name}")
print(f"Action: {action}")
print(f"Signature: {signature[:32]}...")
print(f"Verification: {test_agent.verify_signature(action, signature)}")
print("\n" + "="*50 + "\n")
# Test reputation decay
print("Reputation Decay Simulation:")
print(f"Initial reputation: {test_agent.reputation:.2f}")
for i in range(1, 6):
test_agent.apply_decay(decay_rate=0.05, time_elapsed=1.0)
print(f"After {i} time unit(s): {test_agent.reputation:.2f}")
print("\n" + "="*50 + "\n")
# Metrics
metrics = calculate_reputation_metrics(agents)
print("Reputation Metrics:")
for key, value in metrics.items():
print(f" {key}: {value:.2f}" if isinstance(value, float) else f" {key}: {value}")