forked from lemony-ai/cascadeflow
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmulti_provider.py
More file actions
564 lines (450 loc) Β· 19.6 KB
/
multi_provider.py
File metadata and controls
564 lines (450 loc) Β· 19.6 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
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
"""
Multi-Provider Cascade Example
===============================
Demonstrates mixing multiple AI providers in a single cascade for maximum
flexibility, cost savings, and reliability.
What it demonstrates:
- Mixing OpenAI, Anthropic, and Groq in one cascade
- Provider-specific features and capabilities
- Fallback strategies across providers
- Cost comparison between providers
- Different use cases for each provider
- API key management for multiple providers
Requirements:
- cascadeflow[all]
- At least 2 provider API keys (OpenAI, Anthropic, or Groq)
Setup:
pip install cascadeflow[all]
export OPENAI_API_KEY="sk-..."
export ANTHROPIC_API_KEY="sk-ant-..."
export GROQ_API_KEY="gsk_..."
python examples/multi_provider.py
Why Mix Providers:
1. Cost optimization - Use free/cheap providers first
2. Feature diversity - Different providers excel at different tasks
3. Reliability - Fallback if one provider is down
4. Speed - Fast providers for drafts, accurate for verification
5. Compliance - Some providers better for regulated industries
Provider Comparison:
OpenAI (GPT-4o, GPT-4o-mini):
- β
Best overall quality
- β
Excellent tool calling
- β
Wide model selection
- β Most expensive
- β Rate limits can be strict
Anthropic (Claude 3 family):
- β
Excellent for long context
- β
Strong reasoning
- β
Good for writing tasks
- β Mid-high cost
- β Fewer model options
Groq (Llama 3.1, Mixtral):
- β
Extremely fast (8x faster)
- β
Free tier available
- β
Good for simple queries
- β Limited context window
- β Lower quality on complex tasks
Documentation:
π Provider Guide: docs/guides/providers.md
π Quick Start: docs/guides/quickstart.md
π Examples README: examples/README.md
"""
import asyncio
import os
from cascadeflow import CascadeAgent, ModelConfig
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
# HELPER: Check Available Providers
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
def check_available_providers():
"""Check which provider API keys are available."""
providers = {
"OpenAI": os.getenv("OPENAI_API_KEY"),
"Anthropic": os.getenv("ANTHROPIC_API_KEY"),
"Groq": os.getenv("GROQ_API_KEY"),
}
available = {name: bool(key) for name, key in providers.items()}
print("\nπ Checking available providers:")
for name, is_available in available.items():
status = "β
" if is_available else "β"
print(f" {status} {name}: {'Available' if is_available else 'Not configured'}")
return available
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
# PATTERN 1: Free-First Cascade (Maximum Cost Savings)
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
async def pattern_1_free_first():
"""
Pattern 1: Free-First Cascade
Start with free/cheap providers, escalate only when needed.
Best for: High-volume applications, cost-sensitive workloads
"""
print("\n" + "=" * 70)
print("PATTERN 1: Free-First Cascade")
print("=" * 70)
print("\nStrategy: Groq (free) β GPT-4o-mini (cheap) β GPT-4o (premium)")
print("Best for: Cost optimization, high volume, simple queries\n")
# Build model list based on available providers
models = []
# Tier 1: Groq (free and fast!)
if os.getenv("GROQ_API_KEY"):
models.append(
ModelConfig(
name="llama-3.1-8b-instant",
provider="groq",
cost=0.0, # Free!
speed_ms=200, # Very fast
)
)
print("β
Tier 1: Groq Llama 3.1 8B (FREE, 200ms)")
# Tier 2: OpenAI Mini (cheap)
if os.getenv("OPENAI_API_KEY"):
models.append(
ModelConfig(
name="gpt-4o-mini",
provider="openai",
cost=0.00015, # Very cheap
speed_ms=600,
)
)
print("β
Tier 2: GPT-4o-mini ($0.00015 per request)")
# Tier 3: OpenAI Premium (expensive but best quality)
if os.getenv("OPENAI_API_KEY"):
models.append(
ModelConfig(
name="gpt-4o",
provider="openai",
cost=0.00625, # Premium pricing
speed_ms=1500,
)
)
print("β
Tier 3: GPT-4o ($0.00625 per request)")
if len(models) < 2:
print("\nβ οΈ Need at least 2 providers for cascade")
print(" Set GROQ_API_KEY and/or OPENAI_API_KEY")
return
# Create agent
agent = CascadeAgent(models=models)
# Test queries at different complexity levels
queries = [
("What is 2+2?", "simple"),
("Explain Python in one sentence.", "moderate"),
("Write a technical explanation of quantum computing.", "complex"),
]
total_cost = 0
for query, complexity in queries:
print(f"\n{'β'*70}")
print(f"Query ({complexity}): {query}")
print(f"{'β'*70}")
result = await agent.run(query, max_tokens=200, temperature=0.7)
total_cost += result.total_cost
print(f"\nπ‘ Answer: {result.content[:150]}...")
print("\nπ Stats:")
print(f" Model Used: {result.model_used}")
print(f" Cost: ${result.total_cost:.6f}")
print(f" Latency: {result.latency_ms:.0f}ms")
if result.draft_accepted:
print(" β
Draft Accepted (Verifier skipped!)")
else:
print(" π Cascaded (Both models used)")
print(f"\n{'='*70}")
print(f"π° Pattern 1 Total Cost: ${total_cost:.6f}")
print(f"{'='*70}")
# Show savings vs all-GPT-4o
all_gpt4o_cost = len(queries) * 0.00625
savings = ((all_gpt4o_cost - total_cost) / all_gpt4o_cost) * 100
print(f"\nπ‘ Savings vs all-GPT-4o: {savings:.1f}%")
print(f" All GPT-4o: ${all_gpt4o_cost:.6f}")
print(f" With cascade: ${total_cost:.6f}")
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
# PATTERN 2: Cross-Provider Drafter/Verifier
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
async def pattern_2_cross_provider():
"""
Pattern 2: Cross-Provider Drafter/Verifier
Use one provider for drafting, another for verification.
Best for: Leveraging strengths of different providers
"""
print("\n\n" + "=" * 70)
print("PATTERN 2: Cross-Provider Drafter/Verifier")
print("=" * 70)
print("\nStrategy: Fast provider drafts β Premium provider validates")
print("Best for: Quality assurance, specialized tasks\n")
# Check what we have available
has_groq = bool(os.getenv("GROQ_API_KEY"))
has_openai = bool(os.getenv("OPENAI_API_KEY"))
has_anthropic = bool(os.getenv("ANTHROPIC_API_KEY"))
if not (has_groq or has_openai or has_anthropic):
print("β οΈ Need at least one provider API key")
return
# Build best combination from available providers
models = []
if has_groq:
# Groq as fast drafter
models.append(
ModelConfig(
name="llama-3.3-70b-versatile",
provider="groq",
cost=0.0,
speed_ms=300,
)
)
print("β
Drafter: Groq Llama 3.1 70B (FREE, 300ms)")
if has_anthropic:
# Claude as premium verifier
models.append(
ModelConfig(
name="claude-sonnet-4-5-20250929",
provider="anthropic",
cost=0.003,
speed_ms=1000,
)
)
print("β
Verifier: Claude Sonnet 4.5 ($0.003)")
elif has_openai:
# GPT-4o as fallback verifier
models.append(
ModelConfig(
name="gpt-4o",
provider="openai",
cost=0.00625,
speed_ms=1500,
)
)
print("β
Verifier: GPT-4o ($0.00625)")
if len(models) < 2:
print("\nβ οΈ Need at least 2 providers for this pattern")
print(" Try Pattern 1 or Pattern 3 instead")
return
agent = CascadeAgent(models=models)
# Test with a writing task (good for cross-provider validation)
query = "Write a professional email requesting a meeting with a client."
print(f"\n{'β'*70}")
print(f"Query: {query}")
print(f"{'β'*70}")
result = await agent.run(query, max_tokens=300, temperature=0.7)
print("\nβοΈ Generated Email:\n")
print(result.content)
print("\nπ Stats:")
print(f" Model Used: {result.model_used}")
print(f" Cost: ${result.total_cost:.6f}")
print(f" Latency: {result.latency_ms:.0f}ms")
print(f" Providers: {models[0].provider} β {models[-1].provider}")
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
# PATTERN 3: Provider-Specific Specialization
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
async def pattern_3_specialization():
"""
Pattern 3: Provider-Specific Specialization
Route different types of queries to providers that excel at them.
Best for: Maximizing quality while controlling costs
"""
print("\n\n" + "=" * 70)
print("PATTERN 3: Provider-Specific Specialization")
print("=" * 70)
print("\nStrategy: Match provider strengths to query types")
print("Best for: Quality optimization, diverse workloads\n")
# Build specialized model list
models = []
# OpenAI: Best for technical/code tasks
if os.getenv("OPENAI_API_KEY"):
models.append(
ModelConfig(
name="gpt-4o",
provider="openai",
cost=0.00625,
speed_ms=1500,
)
)
print("β
Technical/Code: GPT-4o (OpenAI)")
# Anthropic: Best for long-form writing
if os.getenv("ANTHROPIC_API_KEY"):
models.append(
ModelConfig(
name="claude-sonnet-4-5-20250929",
provider="anthropic",
cost=0.003,
speed_ms=1000,
)
)
print("β
Writing/Analysis: Claude Sonnet 4.5 (Anthropic)")
# Groq: Best for simple/fast queries
if os.getenv("GROQ_API_KEY"):
models.append(
ModelConfig(
name="llama-3.1-8b-instant",
provider="groq",
cost=0.0,
speed_ms=200,
)
)
print("β
Simple/Fast: Llama 3.1 8B (Groq)")
if len(models) < 2:
print("\nβ οΈ Need at least 2 providers")
return
agent = CascadeAgent(models=models)
# Test queries that showcase different provider strengths
test_cases = [
("Write Python code to sort a list", "Technical (OpenAI strength)"),
("Write a 200-word essay on climate change", "Writing (Anthropic strength)"),
("What is the capital of France?", "Simple fact (Groq strength)"),
]
total_cost = 0
for query, task_type in test_cases:
print(f"\n{'β'*70}")
print(f"Task: {task_type}")
print(f"Query: {query}")
print(f"{'β'*70}")
result = await agent.run(query, max_tokens=250, temperature=0.7)
total_cost += result.total_cost
print("\nπ Result:")
print(
f" Provider: {result.model_used.split('-')[0] if '-' in result.model_used else 'unknown'}"
)
print(f" Model: {result.model_used}")
print(f" Cost: ${result.total_cost:.6f}")
print(f" Latency: {result.latency_ms:.0f}ms")
print(f"\n{'='*70}")
print(f"π° Pattern 3 Total Cost: ${total_cost:.6f}")
print(f"{'='*70}")
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
# PATTERN 4: Reliability with Fallbacks
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
async def pattern_4_reliability():
"""
Pattern 4: Reliability with Fallbacks
Use multiple providers for redundancy and high availability.
Best for: Production systems, critical applications
"""
print("\n\n" + "=" * 70)
print("PATTERN 4: Reliability with Fallbacks")
print("=" * 70)
print("\nStrategy: Multiple providers for redundancy")
print("Best for: High availability, production systems\n")
# Build redundant model list (same tier, different providers)
models = []
if os.getenv("OPENAI_API_KEY"):
models.append(
ModelConfig(
name="gpt-4o-mini",
provider="openai",
cost=0.00015,
)
)
print("β
Primary: GPT-4o-mini (OpenAI)")
if os.getenv("ANTHROPIC_API_KEY"):
models.append(
ModelConfig(
name="claude-3-5-haiku-20241022",
provider="anthropic",
cost=0.001,
)
)
print("β
Fallback: Claude 3.5 Haiku (Anthropic)")
if os.getenv("GROQ_API_KEY"):
models.append(
ModelConfig(
name="llama-3.3-70b-versatile",
provider="groq",
cost=0.0,
)
)
print("β
Fallback: Llama 3.1 70B (Groq)")
if len(models) < 2:
print("\nβ οΈ Need at least 2 providers for fallback pattern")
return
print(f"\nπ‘ Configured {len(models)} providers for redundancy")
print(" If one fails, cascade automatically tries the next\n")
agent = CascadeAgent(models=models)
query = "Explain microservices architecture in 100 words."
print(f"{'β'*70}")
print(f"Query: {query}")
print(f"{'β'*70}")
result = await agent.run(query, max_tokens=150, temperature=0.7)
print(f"\nπ‘ Answer: {result.content[:200]}...")
print("\nπ Stats:")
print(f" Provider Used: {result.model_used}")
print(f" Cost: ${result.total_cost:.6f}")
print(" β
System remained available despite potential failures")
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
# MAIN EXAMPLE
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
async def main():
"""
Main example demonstrating multi-provider patterns.
"""
print("π cascadeflow Multi-Provider Examples")
print("=" * 70)
print("\nDemonstrating 4 patterns for mixing AI providers:")
print(" 1. Free-First Cascade - Maximum cost savings")
print(" 2. Cross-Provider Drafter/Verifier - Quality assurance")
print(" 3. Provider-Specific Specialization - Quality optimization")
print(" 4. Reliability with Fallbacks - High availability")
# Check available providers
available = check_available_providers()
provider_count = sum(available.values())
if provider_count == 0:
print("\nβ No provider API keys found!")
print("\nTo run this example, set at least one API key:")
print(" export OPENAI_API_KEY='sk-...'")
print(" export ANTHROPIC_API_KEY='sk-ant-...'")
print(" export GROQ_API_KEY='gsk_...'")
return
print(f"\nβ
Found {provider_count} provider(s) configured")
if provider_count == 1:
print("\nπ‘ Tip: Set multiple provider API keys to try all patterns!")
# Run available patterns based on configured providers
print("\n" + "=" * 70)
print("RUNNING PATTERNS")
print("=" * 70)
# Pattern 1: Always try (works with any providers)
await pattern_1_free_first()
# Pattern 2: Try if we have at least 2 providers
if provider_count >= 2:
await pattern_2_cross_provider()
# Pattern 3: Try if we have at least 2 providers
if provider_count >= 2:
await pattern_3_specialization()
# Pattern 4: Best with 3 providers, but works with 2
if provider_count >= 2:
await pattern_4_reliability()
# Summary
print("\n\n" + "=" * 70)
print("π KEY TAKEAWAYS")
print("=" * 70)
print("\n1. Provider Selection:")
print(" ββ Groq: Best for speed and cost (FREE!)")
print(" ββ OpenAI: Best for overall quality and features")
print(" ββ Anthropic: Best for long context and reasoning")
print("\n2. Mixing Benefits:")
print(" ββ Cost optimization (use free/cheap first)")
print(" ββ Quality specialization (right provider for task)")
print(" ββ High availability (fallback if provider down)")
print(" ββ Flexibility (switch based on requirements)")
print("\n3. Pattern Selection:")
print(" ββ High volume? β Pattern 1 (Free-First)")
print(" ββ Quality critical? β Pattern 2 (Cross-Provider)")
print(" ββ Diverse tasks? β Pattern 3 (Specialization)")
print(" ββ Production system? β Pattern 4 (Reliability)")
print("\n4. Cost Comparison:")
print(" ββ OpenAI GPT-4o: $0.00625 per request (premium)")
print(" ββ Anthropic Claude: $0.003 per request (mid-tier)")
print(" ββ OpenAI GPT-4o-mini: $0.00015 per request (cheap)")
print(" ββ Groq Llama: $0.00 per request (FREE!)")
print("\n5. Provider Features:")
print(" ββ All support: Text generation, streaming")
print(" ββ OpenAI: Best tool calling, function calling")
print(" ββ Anthropic: 200k token context, XML support")
print(" ββ Groq: 8x faster inference, lower latency")
print("\nπ Learn more:")
print(" β’ docs/guides/providers.md - Provider comparison")
print(" β’ docs/guides/quickstart.md - Getting started")
print(" β’ examples/basic_usage.py - Single provider basics\n")
if __name__ == "__main__":
try:
asyncio.run(main())
except KeyboardInterrupt:
print("\n\nβ οΈ Interrupted by user")
except Exception as e:
print(f"\n\nβ Error: {e}")
import traceback
traceback.print_exc()
print("\nπ‘ Tip: Check your API keys are set correctly")