forked from lemony-ai/cascadeflow
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathproduction-patterns.ts
More file actions
461 lines (389 loc) · 13.1 KB
/
Copy pathproduction-patterns.ts
File metadata and controls
461 lines (389 loc) · 13.1 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
/**
* Production Patterns for cascadeflow
*
* Demonstrates best practices for using cascadeflow in production:
* - Error handling and retries
* - Caching responses
* - Rate limiting
* - Monitoring and logging
* - Cost tracking and budgets
* - Failover strategies
*/
import { CascadeAgent } from '@cascadeflow/core';
import type { CascadeResult } from '@cascadeflow/core';
// ===================================================================
// Pattern 1: Error Handling with Retries
// ===================================================================
async function withRetry<T>(
fn: () => Promise<T>,
maxRetries = 3,
delay = 1000
): Promise<T> {
let lastError: Error | null = null;
for (let attempt = 1; attempt <= maxRetries; attempt++) {
try {
return await fn();
} catch (error: any) {
lastError = error;
console.error(`Attempt ${attempt}/${maxRetries} failed:`, error.message);
if (attempt < maxRetries) {
// Exponential backoff
await new Promise(resolve => setTimeout(resolve, delay * attempt));
}
}
}
throw lastError;
}
async function example1_ErrorHandling() {
console.log('\n📝 Example 1: Error Handling with Retries\n');
const agent = new CascadeAgent({
models: [
{ name: 'claude-haiku-4-5', provider: 'anthropic', cost: 0.001 },
{ name: 'claude-sonnet-4-5', provider: 'anthropic', cost: 0.003 },
],
quality: {
// Production-grade thresholds for reliability
confidenceThresholds: {
simple: 0.6,
moderate: 0.7,
hard: 0.8,
expert: 0.85
},
},
});
try {
const result = await withRetry(
() => agent.run('What is the capital of France?'),
3, // Max 3 retries
1000 // Start with 1s delay
);
console.log('✅ Success:', result.content);
console.log(`Cost: $${result.totalCost.toFixed(6)}`);
} catch (error: any) {
console.error('❌ Failed after all retries:', error.message);
// Log to monitoring service (e.g., Sentry, Datadog)
// sendToMonitoring(error);
}
}
// ===================================================================
// Pattern 2: Response Caching
// ===================================================================
class ResponseCache {
private cache = new Map<string, { result: CascadeResult; timestamp: number }>();
private ttl: number;
constructor(ttlMinutes = 60) {
this.ttl = ttlMinutes * 60 * 1000;
}
get(key: string): CascadeResult | null {
const entry = this.cache.get(key);
if (!entry) return null;
// Check if expired
if (Date.now() - entry.timestamp > this.ttl) {
this.cache.delete(key);
return null;
}
return entry.result;
}
set(key: string, result: CascadeResult): void {
this.cache.set(key, { result, timestamp: Date.now() });
}
clear(): void {
this.cache.clear();
}
}
async function example2_Caching() {
console.log('\n📝 Example 2: Response Caching\n');
const agent = new CascadeAgent({
models: [
{ name: 'claude-haiku-4-5', provider: 'anthropic', cost: 0.001 },
{ name: 'claude-sonnet-4-5', provider: 'anthropic', cost: 0.003 },
],
quality: {
// Balanced thresholds for cached responses
confidenceThresholds: {
simple: 0.6,
moderate: 0.7,
hard: 0.8,
expert: 0.85
},
},
});
const cache = new ResponseCache(60); // 60 minute TTL
async function queryWithCache(query: string): Promise<CascadeResult> {
// Check cache first
const cached = cache.get(query);
if (cached) {
console.log('✅ Cache hit!');
return cached;
}
console.log('❌ Cache miss, fetching...');
const result = await agent.run(query);
cache.set(query, result);
return result;
}
// First call - cache miss
const result1 = await queryWithCache('What is TypeScript?');
console.log(`Cost: $${result1.totalCost.toFixed(6)}`);
// Second call - cache hit (free!)
const result2 = await queryWithCache('What is TypeScript?');
console.log(`Cost: $${result2.totalCost.toFixed(6)}`);
}
// ===================================================================
// Pattern 3: Rate Limiting
// ===================================================================
class RateLimiter {
private tokens: number;
private maxTokens: number;
private refillRate: number;
private lastRefill: number;
constructor(maxRequestsPerMinute: number) {
this.maxTokens = maxRequestsPerMinute;
this.tokens = maxRequestsPerMinute;
this.refillRate = maxRequestsPerMinute / 60000; // tokens per ms
this.lastRefill = Date.now();
}
async acquire(): Promise<void> {
// Refill tokens based on time elapsed
const now = Date.now();
const elapsed = now - this.lastRefill;
this.tokens = Math.min(
this.maxTokens,
this.tokens + elapsed * this.refillRate
);
this.lastRefill = now;
// Wait if no tokens available
if (this.tokens < 1) {
const waitTime = (1 - this.tokens) / this.refillRate;
await new Promise(resolve => setTimeout(resolve, waitTime));
this.tokens = 0;
} else {
this.tokens -= 1;
}
}
}
async function example3_RateLimiting() {
console.log('\n📝 Example 3: Rate Limiting\n');
const agent = new CascadeAgent({
models: [
{ name: 'gpt-4o-mini', provider: 'openai', cost: 0.00015 },
],
quality: {
// Single-model with quality checks
threshold: 0.5, // No cascade, but still validate quality
requireMinimumTokens: 10,
},
});
const rateLimiter = new RateLimiter(10); // 10 requests per minute
async function queryWithRateLimit(query: string): Promise<CascadeResult> {
await rateLimiter.acquire();
return agent.run(query);
}
console.log('Making 3 rate-limited requests...');
const start = Date.now();
for (let i = 1; i <= 3; i++) {
await queryWithRateLimit(`Query ${i}`);
console.log(`✅ Request ${i} completed (${Date.now() - start}ms)`);
}
}
// ===================================================================
// Pattern 4: Cost Tracking and Budgets
// ===================================================================
class CostTracker {
private totalCost = 0;
private budget: number;
private requests: Array<{ query: string; cost: number; timestamp: number }> = [];
constructor(dailyBudget: number) {
this.budget = dailyBudget;
}
async track(query: string, fn: () => Promise<CascadeResult>): Promise<CascadeResult> {
if (this.totalCost >= this.budget) {
throw new Error(`Budget exceeded: $${this.totalCost.toFixed(4)} / $${this.budget}`);
}
const result = await fn();
this.totalCost += result.totalCost;
this.requests.push({
query,
cost: result.totalCost,
timestamp: Date.now(),
});
console.log(`💰 Cost: $${result.totalCost.toFixed(6)} | Total: $${this.totalCost.toFixed(4)} / $${this.budget}`);
return result;
}
getStats() {
return {
totalCost: this.totalCost,
requestCount: this.requests.length,
averageCost: this.totalCost / this.requests.length,
budgetUsed: (this.totalCost / this.budget) * 100,
remainingBudget: this.budget - this.totalCost,
};
}
}
async function example4_CostTracking() {
console.log('\n📝 Example 4: Cost Tracking and Budgets\n');
const agent = new CascadeAgent({
models: [
{ name: 'claude-haiku-4-5', provider: 'anthropic', cost: 0.001 },
{ name: 'claude-sonnet-4-5', provider: 'anthropic', cost: 0.003 },
],
quality: {
// Cost-optimized thresholds to stay within budget
confidenceThresholds: {
simple: 0.5, // More lenient to reduce costs
moderate: 0.65,
hard: 0.75,
expert: 0.85
},
},
});
const tracker = new CostTracker(1.00); // $1 daily budget
try {
await tracker.track('Query 1', () => agent.run('What is AI?'));
await tracker.track('Query 2', () => agent.run('Explain machine learning'));
await tracker.track('Query 3', () => agent.run('What is deep learning?'));
const stats = tracker.getStats();
console.log('\n📊 Statistics:');
console.log(` Total requests: ${stats.requestCount}`);
console.log(` Total cost: $${stats.totalCost.toFixed(6)}`);
console.log(` Average cost: $${stats.averageCost.toFixed(6)}`);
console.log(` Budget used: ${stats.budgetUsed.toFixed(2)}%`);
console.log(` Remaining: $${stats.remainingBudget.toFixed(4)}`);
} catch (error: any) {
console.error('❌', error.message);
}
}
// ===================================================================
// Pattern 5: Monitoring and Logging
// ===================================================================
class QueryLogger {
log(event: string, data: any): void {
const timestamp = new Date().toISOString();
console.log(`[${timestamp}] ${event}:`, JSON.stringify(data, null, 2));
// In production, send to logging service:
// - Datadog
// - CloudWatch
// - Logtail
// - etc.
}
logRequest(query: string, options: any): void {
this.log('REQUEST', { query, options });
}
logResponse(result: CascadeResult): void {
this.log('RESPONSE', {
modelUsed: result.modelUsed,
cost: result.totalCost,
latency: result.latencyMs,
cascaded: result.cascaded,
draftAccepted: result.draftAccepted,
savings: result.savingsPercentage,
});
}
logError(error: Error): void {
this.log('ERROR', {
message: error.message,
stack: error.stack,
});
}
}
async function example5_Monitoring() {
console.log('\n📝 Example 5: Monitoring and Logging\n');
const agent = new CascadeAgent({
models: [
{ name: 'claude-haiku-4-5', provider: 'anthropic', cost: 0.001 },
{ name: 'claude-sonnet-4-5', provider: 'anthropic', cost: 0.003 },
],
quality: {
// Standard production thresholds for monitoring
confidenceThresholds: {
simple: 0.6,
moderate: 0.7,
hard: 0.8,
expert: 0.85
},
},
});
const logger = new QueryLogger();
const query = 'What is quantum computing?';
logger.logRequest(query, { maxTokens: 100 });
try {
const result = await agent.run(query, { maxTokens: 100 });
logger.logResponse(result);
console.log('\n✅ Response:', result.content.substring(0, 100), '...');
} catch (error: any) {
logger.logError(error);
}
}
// ===================================================================
// Pattern 6: Failover Strategy
// ===================================================================
async function example6_Failover() {
console.log('\n📝 Example 6: Failover Strategy\n');
// Primary cascade
const primaryAgent = new CascadeAgent({
models: [
{ name: 'claude-haiku-4-5', provider: 'anthropic', cost: 0.001 },
{ name: 'claude-sonnet-4-5', provider: 'anthropic', cost: 0.003 },
],
quality: {
// Standard thresholds for primary cascade
confidenceThresholds: {
simple: 0.6,
moderate: 0.7,
hard: 0.8,
expert: 0.85
},
},
});
// Fallback cascade (different providers)
const fallbackAgent = new CascadeAgent({
models: [
{ name: 'llama-4-scout', provider: 'groq', cost: 0.00011 },
{ name: 'gpt-4o-mini', provider: 'openai', cost: 0.00015 },
],
quality: {
// More lenient thresholds for fallback (emergency mode)
confidenceThresholds: {
simple: 0.5,
moderate: 0.6,
hard: 0.7,
expert: 0.8
},
},
});
const query = 'Explain neural networks briefly';
try {
console.log('Trying primary cascade...');
const result = await primaryAgent.run(query);
console.log('✅ Primary cascade succeeded');
console.log(`Cost: $${result.totalCost.toFixed(6)}`);
console.log(`Response: ${result.content.substring(0, 100)}...`);
} catch (error: any) {
console.log('❌ Primary cascade failed:', error.message);
console.log('Trying fallback cascade...');
try {
const result = await fallbackAgent.run(query);
console.log('✅ Fallback cascade succeeded');
console.log(`Cost: $${result.totalCost.toFixed(6)}`);
console.log(`Response: ${result.content.substring(0, 100)}...`);
} catch (fallbackError: any) {
console.error('❌ Both cascades failed:', fallbackError.message);
// Last resort: return cached response or error message
}
}
}
// ===================================================================
// Run All Examples
// ===================================================================
async function main() {
console.log('🎯 cascadeflow Production Patterns\n');
console.log('═══════════════════════════════════════════════════\n');
await example1_ErrorHandling();
await example2_Caching();
await example3_RateLimiting();
await example4_CostTracking();
await example5_Monitoring();
await example6_Failover();
console.log('\n═══════════════════════════════════════════════════');
console.log('✅ All examples completed!\n');
}
main().catch(console.error);