-
Notifications
You must be signed in to change notification settings - Fork 343
Expand file tree
/
Copy pathdspy-complete-example.ts
More file actions
735 lines (632 loc) · 28.7 KB
/
dspy-complete-example.ts
File metadata and controls
735 lines (632 loc) · 28.7 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
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
/**
* COMPREHENSIVE DSPy.ts + AgenticSynth Integration Example
*
* E-commerce Product Data Generation with DSPy Optimization
*
* This example demonstrates:
* 1. ✅ Real DSPy.ts (v2.1.1) module usage - ChainOfThought, Predict, Refine
* 2. ✅ Integration with AgenticSynth for baseline data generation
* 3. ✅ BootstrapFewShot optimizer for learning from high-quality examples
* 4. ✅ Quality metrics and comparison (baseline vs optimized)
* 5. ✅ Production-ready error handling and progress tracking
* 6. ✅ Multiple LM provider support (OpenAI, Anthropic)
*
* Usage:
* ```bash
* export OPENAI_API_KEY=sk-...
* export GEMINI_API_KEY=...
* npx tsx examples/dspy-complete-example.ts
* ```
*
* @author rUv
* @license MIT
*/
import 'dotenv/config';
import {
ChainOfThought,
Predict,
Refine,
configureLM,
OpenAILM,
AnthropicLM,
BootstrapFewShot,
exactMatch,
f1Score,
createMetric,
evaluate
} from 'dspy.ts';
import { AgenticSynth } from '../src/index.js';
import type { GenerationResult } from '../src/types.js';
// ============================================================================
// Type Definitions
// ============================================================================
interface Product {
id?: string;
name: string;
category: string;
description: string;
price: number;
rating: number;
features?: string[];
tags?: string[];
}
interface QualityMetrics {
completeness: number;
coherence: number;
persuasiveness: number;
seoQuality: number;
overall: number;
}
interface ComparisonResults {
baseline: {
products: Product[];
avgQuality: number;
metrics: QualityMetrics;
generationTime: number;
cost: number;
};
optimized: {
products: Product[];
avgQuality: number;
metrics: QualityMetrics;
generationTime: number;
cost: number;
};
improvement: {
qualityGain: number;
speedChange: number;
costEfficiency: number;
};
}
// ============================================================================
// Configuration & Setup
// ============================================================================
const CONFIG = {
// API Keys from environment
OPENAI_API_KEY: process.env.OPENAI_API_KEY,
ANTHROPIC_API_KEY: process.env.ANTHROPIC_API_KEY,
GEMINI_API_KEY: process.env.GEMINI_API_KEY,
// Generation settings
SAMPLE_SIZE: 10, // Number of products to generate
TRAINING_EXAMPLES: 5, // Examples for DSPy optimization
// Model configuration
BASELINE_MODEL: 'gemini-2.0-flash-exp',
OPTIMIZED_MODEL: 'gpt-3.5-turbo',
// E-commerce categories
CATEGORIES: [
'Electronics',
'Fashion',
'Home & Garden',
'Sports & Outdoors',
'Books & Media',
'Health & Beauty'
],
// Price ranges
PRICE_RANGES: {
low: { min: 10, max: 50 },
medium: { min: 50, max: 200 },
high: { min: 200, max: 1000 }
}
};
// ============================================================================
// Validation
// ============================================================================
function validateEnvironment(): void {
const missing: string[] = [];
if (!CONFIG.OPENAI_API_KEY) missing.push('OPENAI_API_KEY');
if (!CONFIG.GEMINI_API_KEY) missing.push('GEMINI_API_KEY');
if (missing.length > 0) {
console.error('❌ Missing required environment variables:');
missing.forEach(key => console.error(` - ${key}`));
console.error('\nPlease set these in your .env file or export them:');
console.error('export OPENAI_API_KEY=sk-...');
console.error('export GEMINI_API_KEY=...');
process.exit(1);
}
console.log('✅ Environment validated\n');
}
// ============================================================================
// Quality Metrics
// ============================================================================
/**
* Calculate quality metrics for a product description
*/
function calculateQualityMetrics(product: Product): QualityMetrics {
const description = product.description || '';
const name = product.name || '';
// Completeness: Check if description has key elements
const hasLength = description.length >= 100 && description.length <= 500;
const hasFeatures = description.toLowerCase().includes('feature') ||
description.toLowerCase().includes('benefit');
const hasCTA = description.toLowerCase().includes('buy') ||
description.toLowerCase().includes('order') ||
description.toLowerCase().includes('shop');
const completeness = (
(hasLength ? 0.4 : 0) +
(hasFeatures ? 0.3 : 0) +
(hasCTA ? 0.3 : 0)
);
// Coherence: Check sentence structure and flow
const sentences = description.split(/[.!?]+/).filter(s => s.trim().length > 0);
const avgSentenceLength = sentences.reduce((sum, s) => sum + s.trim().split(/\s+/).length, 0) / Math.max(sentences.length, 1);
const coherence = Math.min(1, avgSentenceLength / 20); // Ideal: 15-25 words per sentence
// Persuasiveness: Check for persuasive language
const persuasiveWords = ['premium', 'exclusive', 'advanced', 'innovative', 'revolutionary', 'best', 'perfect', 'ultimate'];
const foundPersuasive = persuasiveWords.filter(word => description.toLowerCase().includes(word));
const persuasiveness = Math.min(1, foundPersuasive.length / 3);
// SEO Quality: Check if product name appears in description
const nameWords = name.toLowerCase().split(/\s+/);
const descriptionLower = description.toLowerCase();
const nameInDescription = nameWords.filter(word => word.length > 3 && descriptionLower.includes(word)).length;
const seoQuality = Math.min(1, nameInDescription / Math.max(nameWords.length, 1));
// Overall quality score
const overall = (completeness * 0.4 + coherence * 0.2 + persuasiveness * 0.2 + seoQuality * 0.2);
return {
completeness,
coherence,
persuasiveness,
seoQuality,
overall
};
}
/**
* Calculate average quality across multiple products
*/
function calculateAverageQuality(products: Product[]): { avgQuality: number; metrics: QualityMetrics } {
if (products.length === 0) {
return {
avgQuality: 0,
metrics: { completeness: 0, coherence: 0, persuasiveness: 0, seoQuality: 0, overall: 0 }
};
}
const allMetrics = products.map(calculateQualityMetrics);
const avgMetrics: QualityMetrics = {
completeness: allMetrics.reduce((sum, m) => sum + m.completeness, 0) / allMetrics.length,
coherence: allMetrics.reduce((sum, m) => sum + m.coherence, 0) / allMetrics.length,
persuasiveness: allMetrics.reduce((sum, m) => sum + m.persuasiveness, 0) / allMetrics.length,
seoQuality: allMetrics.reduce((sum, m) => sum + m.seoQuality, 0) / allMetrics.length,
overall: allMetrics.reduce((sum, m) => sum + m.overall, 0) / allMetrics.length
};
return {
avgQuality: avgMetrics.overall,
metrics: avgMetrics
};
}
// ============================================================================
// DSPy Custom Metric for Product Quality
// ============================================================================
/**
* DSPy metric function for evaluating product quality
*/
const productQualityMetric = createMetric<{ product: Product }, { score: number }>(
'product-quality',
(example, prediction) => {
if (!prediction?.product) return 0;
const metrics = calculateQualityMetrics(prediction.product);
return metrics.overall;
}
);
// ============================================================================
// Baseline Generation with AgenticSynth
// ============================================================================
/**
* Generate baseline product data using AgenticSynth (Gemini)
*/
async function generateBaseline(count: number): Promise<{ products: Product[]; time: number; cost: number }> {
console.log('📦 Generating baseline data with AgenticSynth (Gemini)...\n');
const startTime = Date.now();
const synth = new AgenticSynth({
provider: 'gemini',
model: CONFIG.BASELINE_MODEL,
apiKey: CONFIG.GEMINI_API_KEY
});
const products: Product[] = [];
for (let i = 0; i < count; i++) {
const category = CONFIG.CATEGORIES[Math.floor(Math.random() * CONFIG.CATEGORIES.length)];
const priceRangeKey = ['low', 'medium', 'high'][Math.floor(Math.random() * 3)] as keyof typeof CONFIG.PRICE_RANGES;
const priceRange = CONFIG.PRICE_RANGES[priceRangeKey];
const prompt = `Generate a compelling e-commerce product for the ${category} category with a price between $${priceRange.min} and $${priceRange.max}. Include:
- Product name (concise, descriptive)
- Detailed description (100-300 words with benefits, features, and call-to-action)
- Exact price (number)
- Rating (1-5)
Return ONLY valid JSON matching this schema:
{
"name": "string",
"category": "string",
"description": "string",
"price": number,
"rating": number
}`;
try {
const result = await synth.generateStructured<Product>({
prompt,
schema: {
type: 'object',
properties: {
name: { type: 'string' },
category: { type: 'string' },
description: { type: 'string' },
price: { type: 'number' },
rating: { type: 'number', minimum: 1, maximum: 5 }
},
required: ['name', 'category', 'description', 'price', 'rating']
},
count: 1
});
if (result.data && result.data.length > 0) {
const product = result.data[0];
product.id = `baseline-${i + 1}`;
products.push(product);
const metrics = calculateQualityMetrics(product);
console.log(` ✓ [${i + 1}/${count}] ${product.name}`);
console.log(` Quality: ${(metrics.overall * 100).toFixed(1)}% | Price: $${product.price.toFixed(2)} | Rating: ${product.rating}/5`);
}
} catch (error) {
console.error(` ✗ [${i + 1}/${count}] Failed:`, error instanceof Error ? error.message : String(error));
}
}
const endTime = Date.now();
const generationTime = (endTime - startTime) / 1000;
// Estimate cost (Gemini Flash is ~$0.10 per 1M tokens)
const avgTokensPerProduct = 500; // Rough estimate
const totalTokens = count * avgTokensPerProduct;
const estimatedCost = (totalTokens / 1_000_000) * 0.10;
console.log(`\n✅ Baseline generation complete: ${products.length}/${count} products in ${generationTime.toFixed(2)}s`);
console.log(`💰 Estimated cost: $${estimatedCost.toFixed(4)}\n`);
return { products, time: generationTime, cost: estimatedCost };
}
// ============================================================================
// DSPy Optimization
// ============================================================================
/**
* Create high-quality training examples for DSPy
*/
function createTrainingExamples(): Array<{ category: string; priceRange: string; product: Product }> {
return [
{
category: 'Electronics',
priceRange: '$100-$500',
product: {
name: 'UltraSound Pro Wireless Headphones',
category: 'Electronics',
description: 'Experience premium audio quality with our UltraSound Pro Wireless Headphones. Featuring advanced active noise cancellation technology, these headphones deliver crystal-clear sound while blocking out ambient noise. With 40-hour battery life and rapid USB-C charging, enjoy uninterrupted listening all day. The ergonomic design ensures comfort during extended wear, while premium materials provide durability. Connect seamlessly via Bluetooth 5.3 for lag-free audio streaming. Perfect for music enthusiasts, remote workers, and travelers. Order now and elevate your audio experience!',
price: 249.99,
rating: 4.7
}
},
{
category: 'Fashion',
priceRange: '$50-$100',
product: {
name: 'EcoLux Organic Cotton T-Shirt Collection',
category: 'Fashion',
description: 'Sustainably crafted from 100% certified organic cotton, our EcoLux T-Shirt Collection combines environmental responsibility with unmatched comfort. Each shirt features a modern fit that flatters all body types, with reinforced stitching for long-lasting wear. The breathable fabric keeps you cool throughout the day while maintaining its shape wash after wash. Available in 12 contemporary colors, these versatile basics complement any wardrobe. By choosing EcoLux, you support ethical farming practices and reduce environmental impact. Shop the collection today and feel the difference quality makes!',
price: 79.99,
rating: 4.5
}
},
{
category: 'Home & Garden',
priceRange: '$200-$500',
product: {
name: 'SmartGrow Indoor Herb Garden System',
category: 'Home & Garden',
description: 'Transform your kitchen into a thriving herb garden with the SmartGrow Indoor System. This innovative hydroponic garden uses automated LED grow lights and intelligent watering to cultivate fresh herbs year-round, regardless of season or climate. Grow basil, cilantro, parsley, and more with zero soil mess. The sleek, modern design complements any kitchen décor while providing fresh ingredients at your fingertips. App-enabled monitoring tracks growth progress and alerts you when water levels are low. Perfect for cooking enthusiasts and health-conscious families. Start growing your culinary garden today!',
price: 349.99,
rating: 4.8
}
},
{
category: 'Sports & Outdoors',
priceRange: '$50-$150',
product: {
name: 'TrailBlazer Ultralight Hiking Backpack',
category: 'Sports & Outdoors',
description: 'Conquer any trail with the TrailBlazer Ultralight Hiking Backpack, engineered for serious adventurers. Weighing just 1.2 pounds yet offering 35 liters of capacity, this pack maximizes storage while minimizing burden. Water-resistant ripstop nylon protects your gear in all weather conditions, while the ergonomic harness system distributes weight evenly for all-day comfort. Multiple compartments keep essentials organized and accessible, including a dedicated hydration sleeve. Reflective accents enhance visibility during dawn and dusk hikes. Whether tackling day trips or multi-day expeditions, TrailBlazer has you covered. Gear up and hit the trail!',
price: 129.99,
rating: 4.6
}
},
{
category: 'Health & Beauty',
priceRange: '$30-$80',
product: {
name: 'RadiantGlow Vitamin C Serum',
category: 'Health & Beauty',
description: 'Reveal your most radiant skin with RadiantGlow Vitamin C Serum, a dermatologist-developed formula that combats signs of aging while brightening your complexion. Our stabilized 20% L-Ascorbic Acid formula penetrates deep to stimulate collagen production, reducing fine lines and wrinkles. Powerful antioxidants protect against environmental damage while hyaluronic acid provides intense hydration. Suitable for all skin types, this lightweight serum absorbs quickly without leaving residue. Visible results appear within 2-4 weeks of consistent use. Cruelty-free and made with natural ingredients. Invest in your skin today and unlock your natural glow!',
price: 59.99,
rating: 4.9
}
}
];
}
/**
* Setup DSPy with OpenAI and create optimized module
*/
async function setupDSPyOptimization(): Promise<{
optimizedModule: any;
setupTime: number;
}> {
console.log('🧠 Setting up DSPy optimization with OpenAI...\n');
const startTime = Date.now();
// Step 1: Configure language model
console.log(' 📡 Configuring OpenAI language model...');
const lm = new OpenAILM({
model: CONFIG.OPTIMIZED_MODEL,
apiKey: CONFIG.OPENAI_API_KEY!,
temperature: 0.7,
maxTokens: 600
});
await lm.init();
configureLM(lm);
console.log(' ✓ Language model configured\n');
// Step 2: Create DSPy module with signature
console.log(' 🔧 Creating ChainOfThought module...');
const productGenerator = new ChainOfThought({
name: 'ProductGenerator',
signature: {
inputs: [
{ name: 'category', type: 'string', required: true, description: 'Product category' },
{ name: 'priceRange', type: 'string', required: true, description: 'Price range (e.g., $100-$500)' }
],
outputs: [
{ name: 'name', type: 'string', required: true, description: 'Product name' },
{ name: 'description', type: 'string', required: true, description: 'Compelling product description' },
{ name: 'price', type: 'number', required: true, description: 'Product price' },
{ name: 'rating', type: 'number', required: true, description: 'Product rating (1-5)' }
]
}
});
console.log(' ✓ Module created\n');
// Step 3: Prepare training examples
console.log(' 📚 Loading training examples...');
const trainingExamples = createTrainingExamples();
console.log(` ✓ Loaded ${trainingExamples.length} high-quality examples\n`);
// Step 4: Create and run optimizer
console.log(' 🎯 Running BootstrapFewShot optimizer...');
const optimizer = new BootstrapFewShot({
metric: productQualityMetric,
maxBootstrappedDemos: CONFIG.TRAINING_EXAMPLES,
maxLabeledDemos: 3,
teacherSettings: { temperature: 0.5 },
maxRounds: 2
});
// Compile the module with training examples
const optimizedModule = await optimizer.compile(productGenerator, trainingExamples);
const endTime = Date.now();
const setupTime = (endTime - startTime) / 1000;
console.log(` ✓ Optimization complete in ${setupTime.toFixed(2)}s\n`);
console.log('✅ DSPy module ready for generation\n');
return { optimizedModule, setupTime };
}
/**
* Generate products using optimized DSPy module
*/
async function generateWithDSPy(
optimizedModule: any,
count: number
): Promise<{ products: Product[]; time: number; cost: number }> {
console.log('🚀 Generating optimized data with DSPy + OpenAI...\n');
const startTime = Date.now();
const products: Product[] = [];
for (let i = 0; i < count; i++) {
const category = CONFIG.CATEGORIES[Math.floor(Math.random() * CONFIG.CATEGORIES.length)];
const priceRangeKey = ['low', 'medium', 'high'][Math.floor(Math.random() * 3)] as keyof typeof CONFIG.PRICE_RANGES;
const priceRange = CONFIG.PRICE_RANGES[priceRangeKey];
const priceRangeStr = `$${priceRange.min}-$${priceRange.max}`;
try {
// Use DSPy module to generate product
const result = await optimizedModule.forward({
category,
priceRange: priceRangeStr
});
// Extract product from result
const product: Product = {
id: `optimized-${i + 1}`,
name: result.name || `Product ${i + 1}`,
category,
description: result.description || '',
price: typeof result.price === 'number' ? result.price : parseFloat(result.price) || priceRange.min,
rating: typeof result.rating === 'number' ? result.rating : parseFloat(result.rating) || 4.0
};
products.push(product);
const metrics = calculateQualityMetrics(product);
console.log(` ✓ [${i + 1}/${count}] ${product.name}`);
console.log(` Quality: ${(metrics.overall * 100).toFixed(1)}% | Price: $${product.price.toFixed(2)} | Rating: ${product.rating}/5`);
} catch (error) {
console.error(` ✗ [${i + 1}/${count}] Failed:`, error instanceof Error ? error.message : String(error));
}
}
const endTime = Date.now();
const generationTime = (endTime - startTime) / 1000;
// Estimate cost (GPT-3.5-turbo is ~$0.50 per 1M input tokens, $1.50 per 1M output tokens)
const avgTokensPerProduct = 700; // Higher than baseline due to CoT reasoning
const totalTokens = count * avgTokensPerProduct;
const estimatedCost = (totalTokens / 1_000_000) * 1.0; // Average of input/output
console.log(`\n✅ Optimized generation complete: ${products.length}/${count} products in ${generationTime.toFixed(2)}s`);
console.log(`💰 Estimated cost: $${estimatedCost.toFixed(4)}\n`);
return { products, time: generationTime, cost: estimatedCost };
}
// ============================================================================
// Comparison & Reporting
// ============================================================================
/**
* Compare baseline vs optimized results
*/
function compareResults(
baselineData: { products: Product[]; time: number; cost: number },
optimizedData: { products: Product[]; time: number; cost: number }
): ComparisonResults {
const baselineQuality = calculateAverageQuality(baselineData.products);
const optimizedQuality = calculateAverageQuality(optimizedData.products);
const qualityGain = ((optimizedQuality.avgQuality - baselineQuality.avgQuality) / baselineQuality.avgQuality) * 100;
const speedChange = ((optimizedData.time - baselineData.time) / baselineData.time) * 100;
const costEfficiency = (optimizedQuality.avgQuality / optimizedData.cost) / (baselineQuality.avgQuality / baselineData.cost) - 1;
return {
baseline: {
products: baselineData.products,
avgQuality: baselineQuality.avgQuality,
metrics: baselineQuality.metrics,
generationTime: baselineData.time,
cost: baselineData.cost
},
optimized: {
products: optimizedData.products,
avgQuality: optimizedQuality.avgQuality,
metrics: optimizedQuality.metrics,
generationTime: optimizedData.time,
cost: optimizedData.cost
},
improvement: {
qualityGain,
speedChange,
costEfficiency: costEfficiency * 100
}
};
}
/**
* Generate comparison report
*/
function generateReport(results: ComparisonResults): void {
console.log('╔════════════════════════════════════════════════════════════════════════╗');
console.log('║ COMPARISON REPORT ║');
console.log('╚════════════════════════════════════════════════════════════════════════╝\n');
// Baseline Results
console.log('📊 BASELINE (AgenticSynth + Gemini)');
console.log('─'.repeat(76));
console.log(`Products Generated: ${results.baseline.products.length}`);
console.log(`Generation Time: ${results.baseline.generationTime.toFixed(2)}s`);
console.log(`Estimated Cost: $${results.baseline.cost.toFixed(4)}`);
console.log(`\nQuality Metrics:`);
console.log(` Overall Quality: ${(results.baseline.avgQuality * 100).toFixed(1)}%`);
console.log(` Completeness: ${(results.baseline.metrics.completeness * 100).toFixed(1)}%`);
console.log(` Coherence: ${(results.baseline.metrics.coherence * 100).toFixed(1)}%`);
console.log(` Persuasiveness: ${(results.baseline.metrics.persuasiveness * 100).toFixed(1)}%`);
console.log(` SEO Quality: ${(results.baseline.metrics.seoQuality * 100).toFixed(1)}%\n`);
// Optimized Results
console.log('🚀 OPTIMIZED (DSPy + OpenAI)');
console.log('─'.repeat(76));
console.log(`Products Generated: ${results.optimized.products.length}`);
console.log(`Generation Time: ${results.optimized.generationTime.toFixed(2)}s`);
console.log(`Estimated Cost: $${results.optimized.cost.toFixed(4)}`);
console.log(`\nQuality Metrics:`);
console.log(` Overall Quality: ${(results.optimized.avgQuality * 100).toFixed(1)}%`);
console.log(` Completeness: ${(results.optimized.metrics.completeness * 100).toFixed(1)}%`);
console.log(` Coherence: ${(results.optimized.metrics.coherence * 100).toFixed(1)}%`);
console.log(` Persuasiveness: ${(results.optimized.metrics.persuasiveness * 100).toFixed(1)}%`);
console.log(` SEO Quality: ${(results.optimized.metrics.seoQuality * 100).toFixed(1)}%\n`);
// Improvement Analysis
console.log('📈 IMPROVEMENT ANALYSIS');
console.log('─'.repeat(76));
const qualitySign = results.improvement.qualityGain >= 0 ? '+' : '';
const speedSign = results.improvement.speedChange >= 0 ? '+' : '';
const efficiencySign = results.improvement.costEfficiency >= 0 ? '+' : '';
console.log(`Quality Gain: ${qualitySign}${results.improvement.qualityGain.toFixed(1)}%`);
console.log(`Speed Change: ${speedSign}${results.improvement.speedChange.toFixed(1)}%`);
console.log(`Cost Efficiency: ${efficiencySign}${results.improvement.costEfficiency.toFixed(1)}%\n`);
// Visual comparison chart
console.log('📊 QUALITY COMPARISON CHART');
console.log('─'.repeat(76));
const maxWidth = 50;
const baselineBar = '█'.repeat(Math.round(results.baseline.avgQuality * maxWidth));
const optimizedBar = '█'.repeat(Math.round(results.optimized.avgQuality * maxWidth));
console.log(`Baseline: ${baselineBar} ${(results.baseline.avgQuality * 100).toFixed(1)}%`);
console.log(`Optimized: ${optimizedBar} ${(results.optimized.avgQuality * 100).toFixed(1)}%\n`);
// Key Insights
console.log('💡 KEY INSIGHTS');
console.log('─'.repeat(76));
if (results.improvement.qualityGain > 10) {
console.log('✓ Significant quality improvement with DSPy optimization');
} else if (results.improvement.qualityGain > 0) {
console.log('✓ Moderate quality improvement observed');
} else {
console.log('⚠ Quality gain is minimal - consider more training examples');
}
if (results.improvement.costEfficiency > 0) {
console.log('✓ Better cost efficiency with optimized approach');
} else {
console.log('⚠ Higher cost per quality point - evaluate trade-offs');
}
console.log('\n' + '═'.repeat(76) + '\n');
}
/**
* Export results to JSON
*/
function exportResults(results: ComparisonResults, filename: string = 'dspy-comparison-results.json'): void {
const outputPath = `/home/user/ruvector/packages/agentic-synth/examples/logs/${filename}`;
try {
const fs = require('fs');
const path = require('path');
// Ensure logs directory exists
const logsDir = path.dirname(outputPath);
if (!fs.existsSync(logsDir)) {
fs.mkdirSync(logsDir, { recursive: true });
}
// Write results
fs.writeFileSync(
outputPath,
JSON.stringify(results, null, 2),
'utf8'
);
console.log(`📁 Results exported to: ${outputPath}\n`);
} catch (error) {
console.error('❌ Failed to export results:', error);
}
}
// ============================================================================
// Main Execution
// ============================================================================
async function main() {
console.log('╔════════════════════════════════════════════════════════════════════════╗');
console.log('║ DSPy.ts + AgenticSynth Integration Example ║');
console.log('║ E-commerce Product Data Generation with Optimization ║');
console.log('╚════════════════════════════════════════════════════════════════════════╝\n');
// Validate environment
validateEnvironment();
try {
// Phase 1: Generate baseline data
console.log('🔷 PHASE 1: BASELINE GENERATION\n');
const baselineData = await generateBaseline(CONFIG.SAMPLE_SIZE);
// Phase 2: Setup DSPy and optimize
console.log('🔷 PHASE 2: DSPy OPTIMIZATION\n');
const { optimizedModule } = await setupDSPyOptimization();
// Phase 3: Generate optimized data
console.log('🔷 PHASE 3: OPTIMIZED GENERATION\n');
const optimizedData = await generateWithDSPy(optimizedModule, CONFIG.SAMPLE_SIZE);
// Phase 4: Compare and report
console.log('🔷 PHASE 4: ANALYSIS & REPORTING\n');
const results = compareResults(baselineData, optimizedData);
generateReport(results);
// Export results
exportResults(results);
console.log('✅ Example complete!\n');
console.log('💡 Next steps:');
console.log(' 1. Review the comparison report above');
console.log(' 2. Check exported JSON for detailed results');
console.log(' 3. Experiment with different training examples');
console.log(' 4. Try other DSPy modules (Refine, ReAct, etc.)');
console.log(' 5. Adjust CONFIG parameters for your use case\n');
} catch (error) {
console.error('\n❌ Example failed:', error);
console.error('\nStack trace:', error instanceof Error ? error.stack : 'No stack trace available');
process.exit(1);
}
}
// Run if executed directly
if (import.meta.url === `file://${process.argv[1]}`) {
main().catch(error => {
console.error('Fatal error:', error);
process.exit(1);
});
}
// Export for testing
export {
generateBaseline,
setupDSPyOptimization,
generateWithDSPy,
compareResults,
calculateQualityMetrics,
calculateAverageQuality,
createTrainingExamples
};