agent0-sdk 0.31__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.
@@ -0,0 +1,445 @@
1
+ """
2
+ Temporary script to discover test data from all subgraph chains.
3
+ Downloads feedback data and finds agents with useful attributes for testing.
4
+ """
5
+
6
+ import json
7
+ import sys
8
+ from typing import Dict, List, Any, Set
9
+ from collections import defaultdict
10
+
11
+ # Add parent directory to path
12
+ sys.path.insert(0, '/Users/madero/Documents/Agent0-sdk/agent0-py')
13
+
14
+ from agent0_sdk import SDK, SearchParams
15
+ from agent0_sdk.core.contracts import DEFAULT_SUBGRAPH_URLS
16
+
17
+ # Supported chains
18
+ SUPPORTED_CHAINS = [11155111, 84532, 80002] # ETH Sepolia, Base Sepolia, Polygon Amoy
19
+
20
+ # RPC URLs (only needed for SDK initialization, not used for subgraph queries)
21
+ RPC_URLS = {
22
+ 11155111: "https://eth-sepolia.g.alchemy.com/v2/7nkA4bJ0tKWcl2-5Wn15c5eRdpGZ8DDr",
23
+ 84532: "https://base-sepolia.g.alchemy.com/v2/7nkA4bJ0tKWcl2-5Wn15c5eRdpGZ8DDr",
24
+ 80002: "https://polygon-amoy.g.alchemy.com/v2/7nkA4bJ0tKWcl2-5Wn15c5eRdpGZ8DDr",
25
+ }
26
+
27
+
28
+ def discover_agents_with_feedback(sdk: SDK, chain_id: int) -> List[Dict[str, Any]]:
29
+ """Discover agents that have feedback on a specific chain."""
30
+ print(f"\nšŸ” Discovering agents with feedback on chain {chain_id}...")
31
+
32
+ agents_with_feedback = []
33
+
34
+ try:
35
+ # Search for agents on this chain
36
+ params = SearchParams()
37
+ params.chains = [chain_id]
38
+ search_result = sdk.indexer.search_agents(params, sort=[], page_size=100)
39
+
40
+ agents = search_result.get('items', [])
41
+ print(f" Found {len(agents)} total agents on chain {chain_id}")
42
+
43
+ # Check each agent for feedback
44
+ for agent in agents:
45
+ # Handle both dict and AgentSummary objects
46
+ if isinstance(agent, dict):
47
+ agent_id = agent.get('agentId') or agent.get('id')
48
+ agent_name = agent.get('name', 'Unknown')
49
+ else:
50
+ agent_id = agent.agentId
51
+ agent_name = agent.name
52
+ try:
53
+ # Try to get feedback for this agent
54
+ feedbacks = sdk.indexer.search_feedback(
55
+ agentId=agent_id,
56
+ first=1, # Just check if any feedback exists
57
+ skip=0
58
+ )
59
+
60
+ if feedbacks and len(feedbacks) > 0:
61
+ # Get full feedback count
62
+ all_feedbacks = sdk.indexer.search_feedback(
63
+ agentId=agent_id,
64
+ first=1000, # Get all feedback
65
+ skip=0
66
+ )
67
+
68
+ agents_with_feedback.append({
69
+ 'chainId': chain_id,
70
+ 'agentId': agent_id,
71
+ 'name': agent_name,
72
+ 'description': agent.get('description', '') if isinstance(agent, dict) else (agent.description if hasattr(agent, 'description') else ''),
73
+ 'feedbackCount': len(all_feedbacks),
74
+ 'feedbacks': all_feedbacks[:10], # Store first 10 for analysis
75
+ 'agent': agent
76
+ })
77
+ print(f" āœ… {agent_name} ({agent_id}): {len(all_feedbacks)} feedback entries")
78
+ except Exception as e:
79
+ # Skip agents that error
80
+ continue
81
+
82
+ print(f" Total agents with feedback: {len(agents_with_feedback)}")
83
+
84
+ except Exception as e:
85
+ print(f" āŒ Error discovering agents: {e}")
86
+
87
+ return agents_with_feedback
88
+
89
+
90
+ def analyze_feedback_data(agents_with_feedback: List[Dict[str, Any]]) -> Dict[str, Any]:
91
+ """Analyze feedback data to extract useful test attributes."""
92
+ print(f"\nšŸ“Š Analyzing feedback data...")
93
+
94
+ analysis = {
95
+ 'totalAgents': len(agents_with_feedback),
96
+ 'totalFeedback': 0,
97
+ 'tags': defaultdict(int),
98
+ 'capabilities': defaultdict(int),
99
+ 'skills': defaultdict(int),
100
+ 'tasks': defaultdict(int),
101
+ 'scores': [],
102
+ 'agents_by_chain': defaultdict(list),
103
+ 'agents_with_high_scores': [],
104
+ 'agents_with_tags': defaultdict(list),
105
+ 'agents_with_capabilities': defaultdict(list),
106
+ 'agents_with_skills': defaultdict(list),
107
+ }
108
+
109
+ for agent_data in agents_with_feedback:
110
+ chain_id = agent_data['chainId']
111
+ agent_id = agent_data['agentId']
112
+ feedbacks = agent_data['feedbacks']
113
+
114
+ analysis['totalFeedback'] += agent_data['feedbackCount']
115
+ analysis['agents_by_chain'][chain_id].append(agent_id)
116
+
117
+ # Analyze each feedback entry
118
+ scores = []
119
+ for feedback in feedbacks:
120
+ # Collect scores
121
+ if feedback.score is not None:
122
+ scores.append(feedback.score)
123
+ analysis['scores'].append(feedback.score)
124
+
125
+ # Collect tags
126
+ if feedback.tags:
127
+ for tag in feedback.tags:
128
+ analysis['tags'][tag] += 1
129
+ if agent_id not in analysis['agents_with_tags'][tag]:
130
+ analysis['agents_with_tags'][tag].append(agent_id)
131
+
132
+ # Collect capabilities
133
+ if feedback.capability:
134
+ analysis['capabilities'][feedback.capability] += 1
135
+ if agent_id not in analysis['agents_with_capabilities'][feedback.capability]:
136
+ analysis['agents_with_capabilities'][feedback.capability].append(agent_id)
137
+
138
+ # Collect skills
139
+ if feedback.skill:
140
+ analysis['skills'][feedback.skill] += 1
141
+ if agent_id not in analysis['agents_with_skills'][feedback.skill]:
142
+ analysis['agents_with_skills'][feedback.skill].append(agent_id)
143
+
144
+ # Collect tasks
145
+ if feedback.task:
146
+ analysis['tasks'][feedback.task] += 1
147
+
148
+ # Calculate average score for this agent
149
+ if scores:
150
+ avg_score = sum(scores) / len(scores)
151
+ if avg_score >= 70: # High score threshold
152
+ analysis['agents_with_high_scores'].append({
153
+ 'agentId': agent_id,
154
+ 'chainId': chain_id,
155
+ 'name': agent_data['name'],
156
+ 'avgScore': avg_score,
157
+ 'feedbackCount': agent_data['feedbackCount']
158
+ })
159
+
160
+ return analysis
161
+
162
+
163
+ def discover_agents_by_reputation(sdk: SDK, chain_id: int) -> List[Dict[str, Any]]:
164
+ """Discover agents using reputation search."""
165
+ print(f"\n⭐ Discovering agents by reputation on chain {chain_id}...")
166
+
167
+ agents = []
168
+
169
+ try:
170
+ result = sdk.searchAgentsByReputation(
171
+ page_size=50,
172
+ chains=[chain_id]
173
+ )
174
+
175
+ found_agents = result.get('items', [])
176
+ print(f" Found {len(found_agents)} agents by reputation")
177
+
178
+ for agent in found_agents:
179
+ avg_score = agent.extras.get('averageScore') if agent.extras else None
180
+ agents.append({
181
+ 'chainId': chain_id,
182
+ 'agentId': agent.agentId,
183
+ 'name': agent.name,
184
+ 'averageScore': avg_score,
185
+ 'agent': agent
186
+ })
187
+ if avg_score:
188
+ print(f" āœ… {agent.name} ({agent.agentId}): Avg Score {avg_score:.2f}")
189
+ else:
190
+ print(f" āš ļø {agent.name} ({agent.agentId}): No average score")
191
+
192
+ except Exception as e:
193
+ print(f" āŒ Error: {e}")
194
+
195
+ return agents
196
+
197
+
198
+ def discover_agents_with_attributes(sdk: SDK, chain_id: int) -> Dict[str, List[Dict[str, Any]]]:
199
+ """Discover agents with specific attributes (MCP tools, A2A skills, etc.)."""
200
+ print(f"\nšŸŽÆ Discovering agents with attributes on chain {chain_id}...")
201
+
202
+ attributes = {
203
+ 'with_mcp_tools': [],
204
+ 'with_a2a_skills': [],
205
+ 'with_ens': [],
206
+ 'with_wallet': [],
207
+ 'active': [],
208
+ 'x402support': [],
209
+ }
210
+
211
+ try:
212
+ params = SearchParams()
213
+ params.chains = [chain_id]
214
+ search_result = sdk.indexer.search_agents(params, sort=[], page_size=100)
215
+
216
+ agents = search_result.get('items', [])
217
+
218
+ for agent in agents:
219
+ # Handle both dict and AgentSummary objects
220
+ if isinstance(agent, dict):
221
+ agent_id = agent.get('agentId') or agent.get('id')
222
+ agent_name = agent.get('name', 'Unknown')
223
+ agent_mcp = agent.get('mcp', False)
224
+ agent_a2a = agent.get('a2a', False)
225
+ agent_ens = agent.get('ens')
226
+ agent_wallet = agent.get('walletAddress')
227
+ agent_active = agent.get('active', False)
228
+ agent_x402 = agent.get('x402support', False)
229
+ mcp_tools = agent.get('mcpTools', [])
230
+ a2a_skills = agent.get('a2aSkills', [])
231
+ else:
232
+ agent_id = agent.agentId
233
+ agent_name = agent.name
234
+ agent_mcp = agent.mcp
235
+ agent_a2a = agent.a2a
236
+ agent_ens = agent.ens
237
+ agent_wallet = agent.walletAddress
238
+ agent_active = agent.active
239
+ agent_x402 = agent.x402support
240
+ mcp_tools = agent.mcpTools if hasattr(agent, 'mcpTools') else []
241
+ a2a_skills = agent.a2aSkills if hasattr(agent, 'a2aSkills') else []
242
+
243
+ agent_info = {
244
+ 'chainId': chain_id,
245
+ 'agentId': agent_id,
246
+ 'name': agent_name,
247
+ }
248
+
249
+ if agent_mcp and mcp_tools:
250
+ attributes['with_mcp_tools'].append({
251
+ **agent_info,
252
+ 'mcpTools': mcp_tools
253
+ })
254
+
255
+ if agent_a2a and a2a_skills:
256
+ attributes['with_a2a_skills'].append({
257
+ **agent_info,
258
+ 'a2aSkills': a2a_skills
259
+ })
260
+
261
+ if agent_ens:
262
+ attributes['with_ens'].append({
263
+ **agent_info,
264
+ 'ens': agent_ens
265
+ })
266
+
267
+ if agent_wallet:
268
+ attributes['with_wallet'].append({
269
+ **agent_info,
270
+ 'walletAddress': agent_wallet
271
+ })
272
+
273
+ if agent_active:
274
+ attributes['active'].append(agent_info)
275
+
276
+ if agent_x402:
277
+ attributes['x402support'].append(agent_info)
278
+
279
+ # Print summary
280
+ for attr_name, attr_list in attributes.items():
281
+ if attr_list:
282
+ print(f" {attr_name}: {len(attr_list)} agents")
283
+
284
+ except Exception as e:
285
+ print(f" āŒ Error: {e}")
286
+
287
+ return attributes
288
+
289
+
290
+ def main():
291
+ print("=" * 80)
292
+ print("šŸ” DISCOVERING TEST DATA FROM ALL SUBGRAPH CHAINS")
293
+ print("=" * 80)
294
+
295
+ all_agents_with_feedback = []
296
+ all_reputation_agents = []
297
+ all_attributes = defaultdict(lambda: defaultdict(list))
298
+
299
+ # Process each chain
300
+ for chain_id in SUPPORTED_CHAINS:
301
+ print(f"\n{'='*80}")
302
+ print(f"šŸ“” Processing Chain {chain_id}")
303
+ print(f"{'='*80}")
304
+
305
+ # Initialize SDK for this chain
306
+ # Use ETH Sepolia RPC for all chains (only needed for SDK init, not used for subgraph queries)
307
+ try:
308
+ sdk = SDK(
309
+ chainId=chain_id,
310
+ rpcUrl=RPC_URLS[11155111], # Use working RPC for all
311
+ signer=None # Read-only
312
+ )
313
+ except Exception as e:
314
+ print(f" āš ļø Failed to initialize SDK for chain {chain_id}: {e}")
315
+ print(f" Skipping chain {chain_id}")
316
+ continue
317
+
318
+ # 1. Discover agents with feedback
319
+ agents_with_feedback = discover_agents_with_feedback(sdk, chain_id)
320
+ all_agents_with_feedback.extend(agents_with_feedback)
321
+
322
+ # 2. Discover agents by reputation
323
+ reputation_agents = discover_agents_by_reputation(sdk, chain_id)
324
+ all_reputation_agents.extend(reputation_agents)
325
+
326
+ # 3. Discover agents with attributes
327
+ attributes = discover_agents_with_attributes(sdk, chain_id)
328
+ for attr_name, attr_list in attributes.items():
329
+ all_attributes[chain_id][attr_name] = attr_list
330
+
331
+ # Analyze all collected data
332
+ print(f"\n{'='*80}")
333
+ print("šŸ“Š COMPREHENSIVE ANALYSIS")
334
+ print(f"{'='*80}")
335
+
336
+ analysis = analyze_feedback_data(all_agents_with_feedback)
337
+
338
+ # Print summary
339
+ print(f"\nšŸ“ˆ SUMMARY:")
340
+ print(f" Total agents with feedback: {analysis['totalAgents']}")
341
+ print(f" Total feedback entries: {analysis['totalFeedback']}")
342
+ print(f" Agents by chain: {dict(analysis['agents_by_chain'])}")
343
+
344
+ # Top tags
345
+ if analysis['tags']:
346
+ print(f"\nšŸ·ļø TOP TAGS (for testing):")
347
+ sorted_tags = sorted(analysis['tags'].items(), key=lambda x: x[1], reverse=True)[:10]
348
+ for tag, count in sorted_tags:
349
+ agents_with_tag = analysis['agents_with_tags'][tag]
350
+ print(f" '{tag}': {count} feedback entries, {len(agents_with_tag)} agents")
351
+ if agents_with_tag:
352
+ print(f" Example agents: {agents_with_tag[:3]}")
353
+
354
+ # Top capabilities
355
+ if analysis['capabilities']:
356
+ print(f"\nšŸ› ļø TOP CAPABILITIES (for testing):")
357
+ sorted_caps = sorted(analysis['capabilities'].items(), key=lambda x: x[1], reverse=True)[:10]
358
+ for cap, count in sorted_caps:
359
+ agents_with_cap = analysis['agents_with_capabilities'][cap]
360
+ print(f" '{cap}': {count} feedback entries, {len(agents_with_cap)} agents")
361
+ if agents_with_cap:
362
+ print(f" Example agents: {agents_with_cap[:3]}")
363
+
364
+ # Top skills
365
+ if analysis['skills']:
366
+ print(f"\nšŸ’” TOP SKILLS (for testing):")
367
+ sorted_skills = sorted(analysis['skills'].items(), key=lambda x: x[1], reverse=True)[:10]
368
+ for skill, count in sorted_skills:
369
+ agents_with_skill = analysis['agents_with_skills'][skill]
370
+ print(f" '{skill}': {count} feedback entries, {len(agents_with_skill)} agents")
371
+ if agents_with_skill:
372
+ print(f" Example agents: {agents_with_skill[:3]}")
373
+
374
+ # Agents with high scores
375
+ if analysis['agents_with_high_scores']:
376
+ print(f"\n⭐ AGENTS WITH HIGH SCORES (avg >= 70):")
377
+ sorted_high = sorted(analysis['agents_with_high_scores'], key=lambda x: x['avgScore'], reverse=True)[:10]
378
+ for agent_info in sorted_high:
379
+ print(f" {agent_info['name']} ({agent_info['agentId']}): {agent_info['avgScore']:.2f} ({agent_info['feedbackCount']} feedback)")
380
+
381
+ # Reputation agents summary
382
+ if all_reputation_agents:
383
+ print(f"\n⭐ REPUTATION SEARCH RESULTS:")
384
+ agents_with_scores = [a for a in all_reputation_agents if a.get('averageScore')]
385
+ if agents_with_scores:
386
+ print(f" Found {len(agents_with_scores)} agents with reputation scores")
387
+ sorted_reputation = sorted(agents_with_scores, key=lambda x: x.get('averageScore', 0) or 0, reverse=True)[:10]
388
+ for agent_info in sorted_reputation:
389
+ print(f" {agent_info['name']} ({agent_info['agentId']}): {agent_info['averageScore']:.2f}")
390
+
391
+ # Save detailed data to JSON file
392
+ output_data = {
393
+ 'agents_with_feedback': [
394
+ {
395
+ 'chainId': a['chainId'],
396
+ 'agentId': a['agentId'],
397
+ 'name': a['name'],
398
+ 'feedbackCount': a['feedbackCount'],
399
+ }
400
+ for a in all_agents_with_feedback
401
+ ],
402
+ 'reputation_agents': all_reputation_agents,
403
+ 'attributes_by_chain': {
404
+ chain_id: {
405
+ attr_name: attr_list
406
+ for attr_name, attr_list in attrs.items()
407
+ }
408
+ for chain_id, attrs in all_attributes.items()
409
+ },
410
+ 'analysis': {
411
+ 'totalAgents': analysis['totalAgents'],
412
+ 'totalFeedback': analysis['totalFeedback'],
413
+ 'topTags': dict(sorted(analysis['tags'].items(), key=lambda x: x[1], reverse=True)[:20]),
414
+ 'topCapabilities': dict(sorted(analysis['capabilities'].items(), key=lambda x: x[1], reverse=True)[:20]),
415
+ 'topSkills': dict(sorted(analysis['skills'].items(), key=lambda x: x[1], reverse=True)[:20]),
416
+ 'agents_by_chain': {str(k): v for k, v in analysis['agents_by_chain'].items()},
417
+ 'agents_with_high_scores': analysis['agents_with_high_scores'],
418
+ 'example_agents_with_tags': {
419
+ tag: agents[:5]
420
+ for tag, agents in list(analysis['agents_with_tags'].items())[:10]
421
+ },
422
+ 'example_agents_with_capabilities': {
423
+ cap: agents[:5]
424
+ for cap, agents in list(analysis['agents_with_capabilities'].items())[:10]
425
+ },
426
+ 'example_agents_with_skills': {
427
+ skill: agents[:5]
428
+ for skill, agents in list(analysis['agents_with_skills'].items())[:10]
429
+ },
430
+ }
431
+ }
432
+
433
+ output_file = '/Users/madero/Documents/Agent0-sdk/agent0-py/tests/test_data_discovery.json'
434
+ with open(output_file, 'w') as f:
435
+ json.dump(output_data, f, indent=2, default=str)
436
+
437
+ print(f"\nšŸ’¾ Detailed data saved to: {output_file}")
438
+ print(f"\n{'='*80}")
439
+ print("āœ… DISCOVERY COMPLETE")
440
+ print(f"{'='*80}")
441
+
442
+
443
+ if __name__ == "__main__":
444
+ main()
445
+