-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathprovider_discovery.py
More file actions
309 lines (253 loc) · 9.52 KB
/
provider_discovery.py
File metadata and controls
309 lines (253 loc) · 9.52 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
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
#!/usr/bin/env python3
"""
Pattern: Provider Discovery
Demonstrates how to discover, filter, and select the best provider
for a given service request.
This pattern shows:
- Service directory queries
- Provider filtering (price, reputation, availability)
- Best provider selection strategies
- Fallback mechanisms
Run: python patterns/provider_discovery.py
"""
import asyncio
import sys
import random
from pathlib import Path
from dataclasses import dataclass
from typing import List, Optional, Callable
from enum import Enum
sys.path.insert(0, str(Path(__file__).parent.parent))
from src.utils.helpers import clear_mock_state, log, log_section
class SelectionStrategy(Enum):
CHEAPEST = "cheapest"
BEST_REPUTATION = "best_reputation"
FASTEST = "fastest"
ROUND_ROBIN = "round_robin"
@dataclass
class ProviderInfo:
"""Information about a provider."""
address: str
name: str
services: List[str]
price_per_request: float # USDC
reputation_score: float # 0-100
avg_response_time_ms: int
success_rate: float # 0-1
is_available: bool
class ProviderDiscovery:
"""Discovers and selects providers for services."""
def __init__(self):
self.providers: List[ProviderInfo] = []
self._round_robin_index = 0
def register(self, provider: ProviderInfo) -> None:
"""Register a provider."""
self.providers.append(provider)
def discover(
self,
service: str,
max_price: Optional[float] = None,
min_reputation: Optional[float] = None,
only_available: bool = True,
) -> List[ProviderInfo]:
"""Discover providers offering a service."""
results = []
for p in self.providers:
# Check service
if service not in p.services:
continue
# Check availability
if only_available and not p.is_available:
continue
# Check price
if max_price and p.price_per_request > max_price:
continue
# Check reputation
if min_reputation and p.reputation_score < min_reputation:
continue
results.append(p)
return results
def select_best(
self,
providers: List[ProviderInfo],
strategy: SelectionStrategy = SelectionStrategy.BEST_REPUTATION,
) -> Optional[ProviderInfo]:
"""Select the best provider using a strategy."""
if not providers:
return None
if strategy == SelectionStrategy.CHEAPEST:
return min(providers, key=lambda p: p.price_per_request)
elif strategy == SelectionStrategy.BEST_REPUTATION:
return max(providers, key=lambda p: p.reputation_score)
elif strategy == SelectionStrategy.FASTEST:
return min(providers, key=lambda p: p.avg_response_time_ms)
elif strategy == SelectionStrategy.ROUND_ROBIN:
selected = providers[self._round_robin_index % len(providers)]
self._round_robin_index += 1
return selected
return providers[0]
def select_with_fallback(
self,
service: str,
strategies: List[SelectionStrategy],
**filters,
) -> Optional[ProviderInfo]:
"""Try multiple strategies until one succeeds."""
for strategy in strategies:
providers = self.discover(service, **filters)
if providers:
selected = self.select_best(providers, strategy)
if selected:
return selected
# Last resort: any available provider
all_providers = self.discover(service, only_available=True)
return all_providers[0] if all_providers else None
async def main() -> None:
log_section("AGIRAILS Pattern - Provider Discovery")
clear_mock_state()
# =====================================================
# Part 1: Setup Mock Providers
# =====================================================
log_section("Part 1: Provider Registry")
discovery = ProviderDiscovery()
# Register mock providers
providers_data = [
ProviderInfo(
address="0xAAAA" + "0" * 36,
name="FastTranslate",
services=["translate", "summarize"],
price_per_request=0.50,
reputation_score=85,
avg_response_time_ms=200,
success_rate=0.95,
is_available=True,
),
ProviderInfo(
address="0xBBBB" + "0" * 36,
name="QualityTranslate",
services=["translate"],
price_per_request=1.00,
reputation_score=98,
avg_response_time_ms=500,
success_rate=0.99,
is_available=True,
),
ProviderInfo(
address="0xCCCC" + "0" * 36,
name="BudgetTranslate",
services=["translate", "ocr"],
price_per_request=0.25,
reputation_score=70,
avg_response_time_ms=800,
success_rate=0.85,
is_available=True,
),
ProviderInfo(
address="0xDDDD" + "0" * 36,
name="OfflineProvider",
services=["translate"],
price_per_request=0.30,
reputation_score=90,
avg_response_time_ms=300,
success_rate=0.92,
is_available=False,
),
]
for p in providers_data:
discovery.register(p)
status = "✅" if p.is_available else "❌"
print(f"{status} {p.name}")
print(f" Services: {', '.join(p.services)}")
print(f" Price: ${p.price_per_request:.2f} | Rep: {p.reputation_score} | Speed: {p.avg_response_time_ms}ms")
print()
# =====================================================
# Part 2: Basic Discovery
# =====================================================
log_section("Part 2: Basic Discovery")
log("🔍", "Finding all 'translate' providers...")
translate_providers = discovery.discover("translate")
print(f" Found: {len(translate_providers)} providers")
for p in translate_providers:
print(f" - {p.name} (${p.price_per_request})")
print()
log("🔍", "Finding 'translate' providers under $0.50...")
cheap_providers = discovery.discover("translate", max_price=0.50)
print(f" Found: {len(cheap_providers)} providers")
for p in cheap_providers:
print(f" - {p.name} (${p.price_per_request})")
print()
log("🔍", "Finding 'translate' providers with reputation >= 90...")
quality_providers = discovery.discover("translate", min_reputation=90)
print(f" Found: {len(quality_providers)} providers")
for p in quality_providers:
print(f" - {p.name} (rep: {p.reputation_score})")
# =====================================================
# Part 3: Selection Strategies
# =====================================================
log_section("Part 3: Selection Strategies")
all_translate = discovery.discover("translate")
strategies = [
(SelectionStrategy.CHEAPEST, "Cheapest"),
(SelectionStrategy.BEST_REPUTATION, "Best Reputation"),
(SelectionStrategy.FASTEST, "Fastest"),
]
for strategy, name in strategies:
selected = discovery.select_best(all_translate, strategy)
if selected:
print(f"{name}: {selected.name}")
print(f" Price: ${selected.price_per_request} | Rep: {selected.reputation_score} | Speed: {selected.avg_response_time_ms}ms")
print()
# Round robin
log("🔄", "Round Robin (3 selections):")
for i in range(3):
selected = discovery.select_best(all_translate, SelectionStrategy.ROUND_ROBIN)
print(f" Selection {i + 1}: {selected.name}")
# =====================================================
# Part 4: Fallback Mechanism
# =====================================================
log_section("Part 4: Fallback Mechanism")
log("🔍", "Looking for premium provider (rep >= 95, price <= $0.30)...")
# This combination might not exist
result = discovery.select_with_fallback(
"translate",
strategies=[
SelectionStrategy.BEST_REPUTATION,
SelectionStrategy.CHEAPEST,
],
min_reputation=95,
max_price=0.30,
)
if result:
print(f" Found: {result.name}")
else:
print(" No exact match, trying fallback...")
# Relax constraints
result = discovery.select_with_fallback(
"translate",
strategies=[SelectionStrategy.BEST_REPUTATION],
min_reputation=80,
)
if result:
print(f" Fallback: {result.name} (relaxed constraints)")
# =====================================================
# Part 5: Integration with SDK
# =====================================================
log_section("Part 5: Integration with SDK")
print("Usage with AGIRAILS SDK:")
print()
print("```python")
print("# Discover best provider")
print("providers = discovery.discover('translate', min_reputation=80)")
print("best = discovery.select_best(providers, SelectionStrategy.BEST_REPUTATION)")
print()
print("# Use with request()")
print("result = await request(")
print(" 'translate',")
print(" input={'text': 'Hello'},")
print(" budget=best.price_per_request * 1.1, # 10% buffer")
print(" provider=best.address, # Specify provider")
print(")")
print("```")
log("🎉", "Provider discovery demo complete!")
if __name__ == "__main__":
asyncio.run(main())