-
Notifications
You must be signed in to change notification settings - Fork 769
Expand file tree
/
Copy pathbatch-processing.ts
More file actions
178 lines (146 loc) · 5.75 KB
/
Copy pathbatch-processing.ts
File metadata and controls
178 lines (146 loc) · 5.75 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
/**
* Example: Batch Processing
*
* Demonstrates batch processing capabilities:
* - Sequential processing with error handling
* - Progress tracking and reporting
* - Batch statistics and cost analysis
* - Different processing strategies
*
* Run: npx tsx examples/nodejs/batch-processing.ts
*/
import { CascadeAgent, BatchStrategy } from '@cascadeflow/core';
async function main() {
console.log('📦 Batch Processing Example\n');
const models = [
{
name: 'gpt-4o-mini',
provider: 'openai' as const,
cost: 0.00015,
},
{
name: 'gpt-4o',
provider: 'openai' as const,
cost: 0.00625,
},
];
const agent = new CascadeAgent({
models,
quality: {
minConfidence: 0.70,
},
});
// ============================================================================
// 1. Sequential Batch Processing
// ============================================================================
console.log('1️⃣ Sequential Batch Processing\n');
const queries = [
'What is TypeScript?',
'Explain async/await in JavaScript.',
'What are design patterns?',
'How does garbage collection work?',
'What is functional programming?',
];
console.log(`Processing ${queries.length} queries sequentially...\n`);
const startTime = Date.now();
const batchResult = await agent.runBatch(queries, {
strategy: BatchStrategy.SEQUENTIAL,
stopOnError: false,
});
const duration = Date.now() - startTime;
console.log(`\n✅ Batch complete in ${(duration / 1000).toFixed(2)}s\n`);
// ============================================================================
// 2. Analyze Results
// ============================================================================
console.log('2️⃣ Batch Results Analysis\n');
console.log(`📊 Summary:`);
console.log(` Total queries: ${batchResult.results.length}`);
console.log(` Successful: ${batchResult.successCount}`);
console.log(` Failed: ${batchResult.failureCount}`);
console.log(` Success rate: ${((batchResult.successCount / batchResult.results.length) * 100).toFixed(1)}%`);
// Calculate costs
const totalCost = batchResult.results
.filter((r) => r !== null)
.reduce((sum, r) => sum + (r?.totalCost || 0), 0);
const avgCost = totalCost / batchResult.successCount;
const avgLatency =
batchResult.results
.filter((r) => r !== null)
.reduce((sum, r) => sum + (r?.latencyMs || 0), 0) / batchResult.successCount;
console.log(`\n💰 Cost Analysis:`);
console.log(` Total cost: $${totalCost.toFixed(6)}`);
console.log(` Average cost per query: $${avgCost.toFixed(6)}`);
console.log(` Average latency: ${avgLatency.toFixed(0)}ms`);
// Draft acceptance rate
const draftAccepted = batchResult.results.filter(
(r) => r !== null && r.draftAccepted
).length;
console.log(`\n🎯 Cascade Performance:`);
console.log(` Draft accepted: ${draftAccepted}/${batchResult.successCount}`);
console.log(
` Acceptance rate: ${((draftAccepted / batchResult.successCount) * 100).toFixed(1)}%`
);
// ============================================================================
// 3. Individual Results
// ============================================================================
console.log('\n3️⃣ Individual Results\n');
batchResult.results.forEach((result, index) => {
if (result !== null) {
console.log(` ✅ Query ${index + 1}: ${queries[index].substring(0, 30)}...`);
console.log(` Model: ${result.modelUsed}`);
console.log(` Cost: $${result.totalCost.toFixed(6)}`);
console.log(` Draft: ${result.draftAccepted ? 'Accepted' : 'Rejected'}`);
} else {
console.log(` ❌ Query ${index + 1}: ${queries[index].substring(0, 30)}...`);
console.log(` Error: Failed`);
}
});
// ============================================================================
// 4. Batch with Custom Configuration
// ============================================================================
console.log('\n4️⃣ Batch with Custom Configuration\n');
const shortQueries = [
'Define API',
'What is REST?',
'Explain HTTP',
];
console.log('Processing with lenient quality thresholds...\n');
const laxAgent = new CascadeAgent({
models,
quality: {
minConfidence: 0.50, // More lenient
requireMinimumTokens: 3,
},
});
const laxResult = await laxAgent.runBatch(shortQueries, {
strategy: BatchStrategy.SEQUENTIAL,
stopOnError: false,
});
console.log(`✅ Completed ${laxResult.successCount}/${shortQueries.length} queries`);
console.log(` Draft acceptance rate: ${((laxResult.results.filter((r) => r !== null && r.draftAccepted).length / laxResult.successCount) * 100).toFixed(1)}%`);
// ============================================================================
// 5. Error Handling
// ============================================================================
console.log('\n5️⃣ Error Handling\n');
// Mix of valid and potentially problematic queries
const mixedQueries = [
'What is Python?',
'', // Empty query (might fail)
'Explain databases.',
];
console.log('Processing batch with error handling...\n');
const errorTestResult = await agent.runBatch(mixedQueries, {
strategy: BatchStrategy.SEQUENTIAL,
stopOnError: false, // Continue even if some fail
});
errorTestResult.results.forEach((result, index) => {
if (result !== null) {
console.log(` ✅ Query ${index + 1}: Success`);
} else {
console.log(` ❌ Query ${index + 1}: Failed`);
}
});
console.log(`\n Success rate: ${((errorTestResult.successCount / mixedQueries.length) * 100).toFixed(1)}%`);
console.log('\n✅ Example complete!');
}
main().catch(console.error);