agent0-sdk 0.2.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
tests/test_sdk.py ADDED
@@ -0,0 +1,238 @@
1
+ """
2
+ Tests for SDK class.
3
+ """
4
+
5
+ import pytest
6
+ from unittest.mock import Mock, patch
7
+
8
+ from agent0_sdk.core.sdk import SDK
9
+ from agent0_sdk.core.models import EndpointType, TrustModel
10
+
11
+
12
+ class TestSDK:
13
+ """Test SDK class."""
14
+
15
+ def test_sdk_initialization(self):
16
+ """Test SDK initialization."""
17
+ with patch('agent0_sdk.core.sdk.Web3Client') as mock_web3:
18
+ mock_web3.return_value.chain_id = 11155111
19
+
20
+ sdk = SDK(
21
+ chain_id=11155111,
22
+ signer="0x1234567890abcdef",
23
+ rpc_url="https://eth-sepolia.g.alchemy.com/v2/test"
24
+ )
25
+
26
+ assert sdk.chain_id == 11155111
27
+ assert sdk.rpc_url == "https://eth-sepolia.g.alchemy.com/v2/test"
28
+ mock_web3.assert_called_once()
29
+
30
+ def test_create_agent(self):
31
+ """Test agent creation."""
32
+ with patch('agent0_sdk.core.sdk.Web3Client') as mock_web3:
33
+ mock_web3.return_value.chain_id = 11155111
34
+
35
+ sdk = SDK(
36
+ chain_id=11155111,
37
+ signer="0x1234567890abcdef",
38
+ rpc_url="https://eth-sepolia.g.alchemy.com/v2/test"
39
+ )
40
+
41
+ agent = sdk.createAgent(
42
+ name="Test Agent",
43
+ description="A test agent",
44
+ image="https://example.com/image.png"
45
+ )
46
+
47
+ assert agent.name == "Test Agent"
48
+ assert agent.description == "A test agent"
49
+ assert agent.image == "https://example.com/image.png"
50
+ assert agent.sdk == sdk
51
+
52
+ def test_registries(self):
53
+ """Test registry resolution."""
54
+ with patch('agent0_sdk.core.sdk.Web3Client') as mock_web3:
55
+ mock_web3.return_value.chain_id = 11155111
56
+
57
+ sdk = SDK(
58
+ chain_id=11155111,
59
+ signer="0x1234567890abcdef",
60
+ rpc_url="https://eth-sepolia.g.alchemy.com/v2/test"
61
+ )
62
+
63
+ registries = sdk.registries()
64
+ assert "IDENTITY" in registries
65
+ assert "REPUTATION" in registries
66
+ assert "VALIDATION" in registries
67
+
68
+ def test_set_chain(self):
69
+ """Test chain switching."""
70
+ with patch('agent0_sdk.core.sdk.Web3Client') as mock_web3:
71
+ mock_web3.return_value.chain_id = 11155111
72
+
73
+ sdk = SDK(
74
+ chain_id=11155111,
75
+ signer="0x1234567890abcdef",
76
+ rpc_url="https://eth-sepolia.g.alchemy.com/v2/test"
77
+ )
78
+
79
+ sdk.set_chain(84532) # Switch to Base Sepolia
80
+ assert sdk.chain_id == 84532
81
+ assert sdk._registries["IDENTITY"] is not None # Should have Base Sepolia registry
82
+
83
+
84
+ class TestAgent:
85
+ """Test Agent class."""
86
+
87
+ def test_agent_endpoint_management(self):
88
+ """Test agent endpoint management."""
89
+ with patch('agent0_sdk.core.sdk.Web3Client') as mock_web3:
90
+ mock_web3.return_value.chain_id = 11155111
91
+
92
+ sdk = SDK(
93
+ chain_id=11155111,
94
+ signer="0x1234567890abcdef",
95
+ rpc_url="https://eth-sepolia.g.alchemy.com/v2/test"
96
+ )
97
+
98
+ agent = sdk.createAgent("Test Agent", "A test agent")
99
+
100
+ # Add MCP endpoint
101
+ agent.setMCP("https://mcp.example.com/")
102
+ assert len(agent.endpoints) == 1
103
+ assert agent.endpoints[0].type == EndpointType.MCP
104
+ assert agent.endpoints[0].value == "https://mcp.example.com/"
105
+ assert agent.endpoints[0].meta["version"] == "2025-06-18"
106
+
107
+ # Add A2A endpoint
108
+ agent.setA2A("https://a2a.example.com/", "1.0")
109
+ assert len(agent.endpoints) == 2
110
+
111
+ # Add ENS endpoint
112
+ agent.setENS("test-agent.eth")
113
+ assert len(agent.endpoints) == 3
114
+ ens_endpoint = next(ep for ep in agent.endpoints if ep.type == EndpointType.ENS)
115
+ assert ens_endpoint.value == "test-agent.eth"
116
+ assert ens_endpoint.meta["version"] == "1.0"
117
+
118
+ # Remove specific endpoint
119
+ agent.removeEndpoint(EndpointType.MCP, "https://mcp.example.com/")
120
+ assert len(agent.endpoints) == 2
121
+ assert agent.endpoints[0].type == EndpointType.A2A
122
+
123
+ # Remove all endpoints
124
+ agent.removeEndpoints()
125
+ assert len(agent.endpoints) == 0
126
+
127
+ def test_agent_trust_models(self):
128
+ """Test agent trust model management."""
129
+ with patch('agent0_sdk.core.sdk.Web3Client') as mock_web3:
130
+ mock_web3.return_value.chain_id = 11155111
131
+
132
+ sdk = SDK(
133
+ chain_id=11155111,
134
+ signer="0x1234567890abcdef",
135
+ rpc_url="https://eth-sepolia.g.alchemy.com/v2/test"
136
+ )
137
+
138
+ agent = sdk.createAgent("Test Agent", "A test agent")
139
+
140
+ # Set trust models using new method
141
+ agent.setTrust(reputation=True, cryptoEconomic=True)
142
+ assert len(agent.trustModels) == 2
143
+ assert TrustModel.REPUTATION in agent.trustModels
144
+ assert TrustModel.CRYPTO_ECONOMIC in agent.trustModels
145
+
146
+ # Set trust models using old method
147
+ agent.trustModels([TrustModel.REPUTATION, "custom_trust"])
148
+ assert len(agent.trustModels) == 2
149
+ assert TrustModel.REPUTATION in agent.trustModels
150
+ assert "custom_trust" in agent.trustModels
151
+
152
+ def test_agent_metadata_management(self):
153
+ """Test agent metadata management."""
154
+ with patch('agent0_sdk.core.sdk.Web3Client') as mock_web3:
155
+ mock_web3.return_value.chain_id = 11155111
156
+
157
+ sdk = SDK(
158
+ chain_id=11155111,
159
+ signer="0x1234567890abcdef",
160
+ rpc_url="https://eth-sepolia.g.alchemy.com/v2/test"
161
+ )
162
+
163
+ agent = sdk.createAgent("Test Agent", "A test agent")
164
+
165
+ # Set metadata
166
+ agent.setMetadata({"key1": "value1", "key2": "value2"})
167
+ assert agent.getMetadata() == {"key1": "value1", "key2": "value2"}
168
+
169
+ # Set single key using setMetadata
170
+ agent.setMetadata({"key3": "value3"})
171
+ assert agent.getMetadata() == {"key1": "value1", "key2": "value2", "key3": "value3"}
172
+
173
+ # Delete key
174
+ agent.delMetadata("key2")
175
+ assert agent.getMetadata() == {"key1": "value1", "key3": "value3"}
176
+
177
+ def test_agent_info_update(self):
178
+ """Test agent info updates."""
179
+ with patch('agent0_sdk.core.sdk.Web3Client') as mock_web3:
180
+ mock_web3.return_value.chain_id = 11155111
181
+
182
+ sdk = SDK(
183
+ chain_id=11155111,
184
+ signer="0x1234567890abcdef",
185
+ rpc_url="https://eth-sepolia.g.alchemy.com/v2/test"
186
+ )
187
+
188
+ agent = sdk.createAgent("Test Agent", "A test agent")
189
+
190
+ # Update info
191
+ agent.updateInfo(
192
+ name="Updated Agent",
193
+ description="An updated agent",
194
+ image="https://example.com/new-image.png"
195
+ )
196
+
197
+ assert agent.name == "Updated Agent"
198
+ assert agent.description == "An updated agent"
199
+ assert agent.image == "https://example.com/new-image.png"
200
+
201
+ # Set wallet address
202
+ agent.setAgentWallet("0x1234567890abcdef")
203
+ assert agent.walletAddress == "0x1234567890abcdef"
204
+
205
+ def test_agent_json_serialization(self):
206
+ """Test agent JSON serialization."""
207
+ with patch('agent0_sdk.core.sdk.Web3Client') as mock_web3:
208
+ mock_web3.return_value.chain_id = 11155111
209
+
210
+ sdk = SDK(
211
+ chain_id=11155111,
212
+ signer="0x1234567890abcdef",
213
+ rpc_url="https://eth-sepolia.g.alchemy.com/v2/test"
214
+ )
215
+
216
+ agent = sdk.createAgent("Test Agent", "A test agent")
217
+ agent.setMCP("https://mcp.example.com/")
218
+ agent.trustModels([TrustModel.REPUTATION])
219
+
220
+ json_data = agent.to_json()
221
+ assert isinstance(json_data, str)
222
+ assert "Test Agent" in json_data
223
+ assert "MCP" in json_data
224
+ assert "reputation" in json_data
225
+
226
+ # Test x402 support
227
+ agent.setX402Support(True)
228
+ assert agent.x402support is True
229
+
230
+ json_data_with_x402 = agent.to_json()
231
+ assert "x402support" in json_data_with_x402
232
+
233
+ # Test active status
234
+ agent.setActive(True)
235
+ assert agent.active is True
236
+
237
+ agent.setActive(False)
238
+ assert agent.active is False
tests/test_search.py ADDED
@@ -0,0 +1,271 @@
1
+ """
2
+ Test for Agent Search and Discovery using Subgraph
3
+ Tests various search and filtering capabilities for discovering agents and their reputation.
4
+
5
+ Flow:
6
+ 1. Get a specific agent by ID
7
+ 2. Search agents by name (partial match)
8
+ 3. Search agents by capabilities (MCP tools)
9
+ 4. Search agents by skills (A2A)
10
+ 5. Search agents by ENS domain
11
+ 6. Search agents by active status
12
+ 7. Combine multiple filters (capabilities + skills)
13
+ 8. Search agents by reputation with minimum average score
14
+ 9. Search agents by reputation with specific tags
15
+ 10. Search agents by reputation with capability filtering
16
+ 11. Advanced: Find top-rated agents with specific skills
17
+ 12. Advanced: Find agents with multiple requirements
18
+ """
19
+
20
+ import logging
21
+ import time
22
+ import random
23
+ import sys
24
+
25
+ # Configure logging: root logger at WARNING to suppress noisy dependencies
26
+ logging.basicConfig(
27
+ level=logging.WARNING,
28
+ format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
29
+ datefmt='%Y-%m-%d %H:%M:%S',
30
+ handlers=[logging.StreamHandler(sys.stdout)]
31
+ )
32
+
33
+ # Set debug level ONLY for agent0_sdk
34
+ logging.getLogger('agent0_sdk').setLevel(logging.DEBUG)
35
+ logging.getLogger('agent0_sdk.core').setLevel(logging.DEBUG)
36
+
37
+ from agent0_sdk import SDK, SearchParams
38
+ from config import CHAIN_ID, RPC_URL, AGENT_PRIVATE_KEY, SUBGRAPH_URL, AGENT_ID, print_config
39
+
40
+
41
+ def main():
42
+ print("šŸ” Testing Agent Search and Discovery")
43
+ print_config()
44
+ print("=" * 60)
45
+
46
+ # Initialize SDK without signer (read-only operations)
47
+ sdk = SDK(
48
+ chainId=CHAIN_ID,
49
+ rpcUrl=RPC_URL
50
+ )
51
+
52
+ print(f"\nšŸ“ Step 1: Get Agent by ID")
53
+ print("-" * 60)
54
+ try:
55
+ agent = sdk.getAgent(AGENT_ID)
56
+ print(f"āœ… Agent found: {agent.name}")
57
+ print(f" Description: {agent.description[:80] if agent.description else 'N/A'}...")
58
+ print(f" Chain ID: {agent.chainId}")
59
+ print(f" Active: {agent.active}")
60
+ print(f" ENS: {agent.ens}")
61
+ print(f" Agent ID: {agent.agentId}")
62
+ # MCP and A2A support determined by endpoint presence
63
+ if hasattr(agent, 'mcpEndpoint') and agent.mcpEndpoint:
64
+ print(f" MCP: {agent.mcpEndpoint}")
65
+ if hasattr(agent, 'a2aEndpoint') and agent.a2aEndpoint:
66
+ print(f" A2A: {agent.a2aEndpoint}")
67
+ except Exception as e:
68
+ print(f"āŒ Failed to get agent: {e}")
69
+
70
+ print(f"\nšŸ“ Step 2: Search Agents by Name (Partial Match)")
71
+ print("-" * 60)
72
+ try:
73
+ results = sdk.searchAgents(name="Test")
74
+ agents = results.get('items', [])
75
+ print(f"āœ… Found {len(agents)} agent(s) with name matching 'Test'")
76
+ for i, agent in enumerate(agents[:3], 1):
77
+ agent_id = agent.get('agentId', agent.get('id', 'N/A'))
78
+ print(f" {i}. {agent['name']} (ID: {agent_id})")
79
+ if agent.get('description'):
80
+ print(f" {agent['description'][:60]}...")
81
+ except Exception as e:
82
+ print(f"āŒ Failed to search by name: {e}")
83
+
84
+ print(f"\nšŸ“ Step 3: Search Agents by MCP Tools (Capabilities)")
85
+ print("-" * 60)
86
+ try:
87
+ # Using capabilities from test_feedback.py: data_analysis, code_generation, natural_language_understanding, problem_solving, communication
88
+ results = sdk.searchAgents(mcpTools=["data_analysis"])
89
+ agents = results.get('items', [])
90
+ print(f"āœ… Found {len(agents)} agent(s) with 'data_analysis' capability")
91
+ for i, agent in enumerate(agents[:3], 1):
92
+ print(f" {i}. {agent['name']}")
93
+ if agent.get('mcpTools'):
94
+ print(f" Tools: {', '.join(agent['mcpTools'][:3])}...")
95
+ except Exception as e:
96
+ print(f"āŒ Failed to search by capabilities: {e}")
97
+
98
+ print(f"\nšŸ“ Step 4: Search Agents by A2A Skills")
99
+ print("-" * 60)
100
+ try:
101
+ # Using skills from test_feedback.py: python, javascript, machine_learning, web_development, cloud_computing
102
+ results = sdk.searchAgents(a2aSkills=["javascript"])
103
+ agents = results.get('items', [])
104
+ print(f"āœ… Found {len(agents)} agent(s) with 'javascript' skill")
105
+ for i, agent in enumerate(agents[:3], 1):
106
+ print(f" {i}. {agent['name']}")
107
+ if agent.get('a2aSkills'):
108
+ print(f" Skills: {', '.join(agent['a2aSkills'][:3])}...")
109
+ except Exception as e:
110
+ print(f"āŒ Failed to search by skills: {e}")
111
+
112
+ print(f"\nšŸ“ Step 5: Search Agents by ENS Domain")
113
+ print("-" * 60)
114
+ try:
115
+ results = sdk.searchAgents(ens="test")
116
+ agents = results.get('items', [])
117
+ print(f"āœ… Found {len(agents)} agent(s) with ENS matching 'test'")
118
+ for i, agent in enumerate(agents[:3], 1):
119
+ print(f" {i}. {agent['name']}")
120
+ if agent.get('ens'):
121
+ print(f" ENS: {agent['ens']}")
122
+ except Exception as e:
123
+ print(f"āŒ Failed to search by ENS: {e}")
124
+
125
+ print(f"\nšŸ“ Step 6: Search Only Active Agents")
126
+ print("-" * 60)
127
+ try:
128
+ results = sdk.searchAgents(active=True, page_size=10)
129
+ agents = results.get('items', [])
130
+ print(f"āœ… Found {len(agents)} active agent(s)")
131
+ for i, agent in enumerate(agents[:3], 1):
132
+ print(f" {i}. {agent['name']} - {agent.get('totalFeedback', 0)} feedback")
133
+ except Exception as e:
134
+ print(f"āŒ Failed to search active agents: {e}")
135
+
136
+ print(f"\nšŸ“ Step 7: Search Agents with Multiple Filters (Capabilities + Skills)")
137
+ print("-" * 60)
138
+ try:
139
+ # Using capabilities and skills from test_feedback.py:
140
+ # Capabilities: data_analysis, code_generation, natural_language_understanding, problem_solving, communication
141
+ # Skills: python, javascript, machine_learning, web_development, cloud_computing
142
+ results = sdk.searchAgents(
143
+ mcpTools=["communication"],
144
+ a2aSkills=["python"]
145
+ )
146
+ agents = results.get('items', [])
147
+ print(f"āœ… Found {len(agents)} agent(s) with 'communication' capability AND 'python' skill")
148
+ for i, agent in enumerate(agents[:3], 1):
149
+ print(f" {i}. {agent['name']}")
150
+ except Exception as e:
151
+ print(f"āŒ Failed to search with multiple filters: {e}")
152
+
153
+ print(f"\nšŸ“ Step 8: Search Agents by Reputation (Minimum Average Score)")
154
+ print("-" * 60)
155
+ try:
156
+ results = sdk.searchAgentsByReputation(minAverageScore=80)
157
+ agents = results.get('items', [])
158
+ print(f"āœ… Found {len(agents)} agent(s) with average score >= 80")
159
+ for i, agent in enumerate(agents[:3], 1):
160
+ # AgentSummary object - use attributes, not dict.get()
161
+ avg_score = agent.extras.get('averageScore', 'N/A') if agent.extras else 'N/A'
162
+ print(f" {i}. {agent.name}")
163
+ print(f" Average Score: {avg_score}")
164
+ print(f" Agent ID: {agent.agentId}")
165
+ except Exception as e:
166
+ print(f"āŒ Failed to search by reputation score: {e}")
167
+
168
+ print(f"\nšŸ“ Step 9: Search Agents by Reputation with Specific Tags")
169
+ print("-" * 60)
170
+ try:
171
+ # Using tags that actually exist in feedback: "enterprise" appears frequently
172
+ # Note: GraphQL query has known issue with mixing filters, so using includeRevoked=True as workaround
173
+ # which may affect results, but at least the query will execute
174
+ results = sdk.searchAgentsByReputation(
175
+ tags=["enterprise"],
176
+ minAverageScore=0, # No threshold to see any results
177
+ includeRevoked=True # Workaround for GraphQL query builder issue
178
+ )
179
+ agents = results.get('items', [])
180
+ print(f"āœ… Found {len(agents)} agent(s) with 'enterprise' tag")
181
+ for i, agent in enumerate(agents[:3], 1):
182
+ # AgentSummary object - use attributes
183
+ avg_score = agent.extras.get('averageScore', 'N/A') if agent.extras else 'N/A'
184
+ print(f" {i}. {agent.name} - Avg: {avg_score}")
185
+ except Exception as e:
186
+ print(f"āŒ Failed to search by reputation tags: {e}")
187
+
188
+ print(f"\nšŸ“ Step 10: Search Agents by Reputation with Capability Filtering")
189
+ print("-" * 60)
190
+ try:
191
+ # Using capabilities that actually exist in feedback: code_generation, problem_solving, data_analysis
192
+ results = sdk.searchAgentsByReputation(
193
+ capabilities=["code_generation"],
194
+ minAverageScore=0 # No threshold to see any results
195
+ )
196
+ agents = results.get('items', [])
197
+ print(f"āœ… Found {len(agents)} agent(s) with 'code_generation' capability")
198
+ for i, agent in enumerate(agents[:3], 1):
199
+ avg_score = agent.extras.get('averageScore', 'N/A') if hasattr(agent, 'extras') and agent.extras else 'N/A'
200
+ print(f" {i}. {agent.name}")
201
+ print(f" Avg Score: {avg_score}")
202
+ except Exception as e:
203
+ print(f"āŒ Failed to search by reputation with capabilities: {e}")
204
+
205
+ print(f"\nšŸ“ Step 11: Advanced - Find Top-Rated Agents with Specific Skills")
206
+ print("-" * 60)
207
+ try:
208
+ # Using skills that actually exist in feedback: python, machine_learning, cloud_computing, web_development
209
+ results = sdk.searchAgentsByReputation(
210
+ skills=["python"],
211
+ minAverageScore=0 # No threshold to see any results
212
+ )
213
+ agents = results.get('items', [])
214
+ print(f"āœ… Found {len(agents)} agent(s) with 'python' skill")
215
+ for i, agent in enumerate(agents[:3], 1):
216
+ # AgentSummary object - use attributes
217
+ avg_score = agent.extras.get('averageScore', 'N/A') if agent.extras else 'N/A'
218
+ print(f" {i}. {agent.name}")
219
+ print(f" Average Score: {avg_score}")
220
+ if agent.a2aSkills:
221
+ print(f" Skills: {', '.join(agent.a2aSkills[:3])}")
222
+ except Exception as e:
223
+ print(f"āŒ Failed advanced skill search: {e}")
224
+
225
+ print(f"\nšŸ“ Step 12: Advanced - Complex Multi-Criteria Search")
226
+ print("-" * 60)
227
+ try:
228
+ results = sdk.searchAgents(name="Test", active=True, page_size=10)
229
+ agents = results.get('items', [])
230
+ print(f"āœ… Found {len(agents)} agent(s) matching multiple criteria")
231
+ for i, agent in enumerate(agents[:3], 1):
232
+ print(f" {i}. {agent['name']}")
233
+ print(f" Active: {agent.get('active', False)}, Feedback: {agent.get('totalFeedback', 0)}")
234
+ if agent.get('ens'):
235
+ print(f" ENS: {agent['ens']}")
236
+ except Exception as e:
237
+ print(f"āŒ Failed complex search: {e}")
238
+
239
+ print(f"\nšŸ“ Step 13: Pagination Test (First 5 Agents)")
240
+ print("-" * 60)
241
+ try:
242
+ results = sdk.searchAgents(page_size=5)
243
+ agents = results.get('items', [])
244
+ print(f"āœ… Retrieved first page: {len(agents)} agent(s)")
245
+ for i, agent in enumerate(agents, 1):
246
+ agent_id = agent.get('agentId', agent.get('id', 'N/A'))
247
+ print(f" {i}. {agent['name']} (ID: {agent_id})")
248
+ except Exception as e:
249
+ print(f"āŒ Failed pagination test: {e}")
250
+
251
+ print(f"\nšŸ“ Step 14: Sort by Activity (Most Recent)")
252
+ print("-" * 60)
253
+ try:
254
+ results = sdk.searchAgents(page_size=10, sort=["updatedAt:desc"])
255
+ agents = results.get('items', [])
256
+ if agents:
257
+ print(f"āœ… Retrieved {len(agents)} agents")
258
+ print(f" Most recent activity IDs:")
259
+ for i, agent in enumerate(agents[:5], 1):
260
+ agent_id = agent.get('agentId', agent.get('id', 'N/A'))
261
+ print(f" {i}. ID {agent_id}: {agent['name']}")
262
+ except Exception as e:
263
+ print(f"āŒ Failed activity sort: {e}")
264
+
265
+ print("\n" + "=" * 60)
266
+ print("āœ… Search Tests Completed!")
267
+ print("=" * 60)
268
+
269
+
270
+ if __name__ == "__main__":
271
+ main()