societyai 0.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (114) hide show
  1. package/CHANGELOG.md +111 -0
  2. package/LICENSE +21 -0
  3. package/README.md +879 -0
  4. package/dist/builder.d.ts +181 -0
  5. package/dist/builder.d.ts.map +1 -0
  6. package/dist/builder.js +667 -0
  7. package/dist/builder.js.map +1 -0
  8. package/dist/config.d.ts +43 -0
  9. package/dist/config.d.ts.map +1 -0
  10. package/dist/config.js +11 -0
  11. package/dist/config.js.map +1 -0
  12. package/dist/context.d.ts +107 -0
  13. package/dist/context.d.ts.map +1 -0
  14. package/dist/context.js +319 -0
  15. package/dist/context.js.map +1 -0
  16. package/dist/errors.d.ts +31 -0
  17. package/dist/errors.d.ts.map +1 -0
  18. package/dist/errors.js +85 -0
  19. package/dist/errors.js.map +1 -0
  20. package/dist/events.d.ts +219 -0
  21. package/dist/events.d.ts.map +1 -0
  22. package/dist/events.js +395 -0
  23. package/dist/events.js.map +1 -0
  24. package/dist/graph.d.ts +104 -0
  25. package/dist/graph.d.ts.map +1 -0
  26. package/dist/graph.js +366 -0
  27. package/dist/graph.js.map +1 -0
  28. package/dist/index.d.ts +28 -0
  29. package/dist/index.d.ts.map +1 -0
  30. package/dist/index.js +113 -0
  31. package/dist/index.js.map +1 -0
  32. package/dist/logger.d.ts +13 -0
  33. package/dist/logger.d.ts.map +1 -0
  34. package/dist/logger.js +78 -0
  35. package/dist/logger.js.map +1 -0
  36. package/dist/memory.d.ts +146 -0
  37. package/dist/memory.d.ts.map +1 -0
  38. package/dist/memory.js +353 -0
  39. package/dist/memory.js.map +1 -0
  40. package/dist/metrics.d.ts +143 -0
  41. package/dist/metrics.d.ts.map +1 -0
  42. package/dist/metrics.js +271 -0
  43. package/dist/metrics.js.map +1 -0
  44. package/dist/middleware.d.ts +147 -0
  45. package/dist/middleware.d.ts.map +1 -0
  46. package/dist/middleware.js +484 -0
  47. package/dist/middleware.js.map +1 -0
  48. package/dist/models.d.ts +32 -0
  49. package/dist/models.d.ts.map +1 -0
  50. package/dist/models.js +211 -0
  51. package/dist/models.js.map +1 -0
  52. package/dist/patterns.d.ts +6 -0
  53. package/dist/patterns.d.ts.map +1 -0
  54. package/dist/patterns.js +68 -0
  55. package/dist/patterns.js.map +1 -0
  56. package/dist/pipeline.d.ts +84 -0
  57. package/dist/pipeline.d.ts.map +1 -0
  58. package/dist/pipeline.js +569 -0
  59. package/dist/pipeline.js.map +1 -0
  60. package/dist/retry.d.ts +5 -0
  61. package/dist/retry.d.ts.map +1 -0
  62. package/dist/retry.js +70 -0
  63. package/dist/retry.js.map +1 -0
  64. package/dist/society.d.ts +94 -0
  65. package/dist/society.d.ts.map +1 -0
  66. package/dist/society.js +721 -0
  67. package/dist/society.js.map +1 -0
  68. package/dist/strategies.d.ts +55 -0
  69. package/dist/strategies.d.ts.map +1 -0
  70. package/dist/strategies.js +678 -0
  71. package/dist/strategies.js.map +1 -0
  72. package/dist/tools.d.ts +88 -0
  73. package/dist/tools.d.ts.map +1 -0
  74. package/dist/tools.js +366 -0
  75. package/dist/tools.js.map +1 -0
  76. package/dist/types.d.ts +213 -0
  77. package/dist/types.d.ts.map +1 -0
  78. package/dist/types.js +19 -0
  79. package/dist/types.js.map +1 -0
  80. package/dist/validation.d.ts +64 -0
  81. package/dist/validation.d.ts.map +1 -0
  82. package/dist/validation.js +334 -0
  83. package/dist/validation.js.map +1 -0
  84. package/dist/worker-pool.d.ts +17 -0
  85. package/dist/worker-pool.d.ts.map +1 -0
  86. package/dist/worker-pool.js +80 -0
  87. package/dist/worker-pool.js.map +1 -0
  88. package/docs/README.md +468 -0
  89. package/docs/advanced.md +616 -0
  90. package/docs/aggregation-strategies.md +926 -0
  91. package/docs/api-reference.md +771 -0
  92. package/docs/architecture.md +648 -0
  93. package/docs/context-system.md +642 -0
  94. package/docs/event-system.md +1047 -0
  95. package/docs/examples.md +576 -0
  96. package/docs/getting-started.md +564 -0
  97. package/docs/graph-execution.md +389 -0
  98. package/docs/memory-system.md +497 -0
  99. package/docs/metrics-observability.md +560 -0
  100. package/docs/middleware-system.md +1038 -0
  101. package/docs/migration.md +296 -0
  102. package/docs/pipeline-patterns.md +761 -0
  103. package/docs/structured-output.md +612 -0
  104. package/docs/tool-calling.md +491 -0
  105. package/docs/workflows.md +740 -0
  106. package/examples/README.md +234 -0
  107. package/examples/advanced-patterns.ts +115 -0
  108. package/examples/complete-integration.ts +327 -0
  109. package/examples/graph-workflow.ts +161 -0
  110. package/examples/memory-system.ts +155 -0
  111. package/examples/metrics-tracking.ts +243 -0
  112. package/examples/structured-output.ts +231 -0
  113. package/examples/tool-calling.ts +163 -0
  114. package/package.json +94 -0
@@ -0,0 +1,761 @@
1
+ # Pipeline Patterns
2
+
3
+ Les pipelines de SocietyAI fournissent des patterns composables pour orchestrer l'exécution des agents avec des modèles d'exécution pré-configurés.
4
+
5
+ ## Table des Matières
6
+
7
+ - [Vue d'ensemble](#vue-densemble)
8
+ - [Pipeline Builder](#pipeline-builder)
9
+ - [Patterns de Base](#patterns-de-base)
10
+ - [Patterns Avancés](#patterns-avancés)
11
+ - [Built-in Pipelines](#built-in-pipelines)
12
+ - [Composition de Pipelines](#composition-de-pipelines)
13
+ - [Patterns Pré-configurés](#patterns-pré-configurés)
14
+ - [Exemples Complets](#exemples-complets)
15
+
16
+ ## Vue d'ensemble
17
+
18
+ Les pipelines définissent le flux et la coordination des agents. Ils permettent de:
19
+
20
+ - **Orchestrer** l'exécution séquentielle ou parallèle
21
+ - **Router** dynamiquement vers des agents appropriés
22
+ - **Diviser** et traiter les tâches en parallèle
23
+ - **Agréger** les résultats de multiples agents
24
+ - **Composer** des workflows complexes
25
+ - **Réutiliser** des patterns communs
26
+
27
+ ### Principes de Design
28
+
29
+ - **Model-agnostic**: Fonctionne avec n'importe quel modèle AI
30
+ - **Composable**: Les pipelines peuvent être imbriqués et combinés
31
+ - **Type-safe**: Support complet TypeScript
32
+ - **Zero runtime deps**: Implémentation pure TypeScript
33
+
34
+ ## Pipeline Builder
35
+
36
+ ### Création de Base
37
+
38
+ ```typescript
39
+ import { PipelineBuilder } from 'societyai';
40
+
41
+ const pipeline = PipelineBuilder.create('my-pipeline')
42
+ .withTimeout(30000) // 30 secondes
43
+ .then('agent-1')
44
+ .then('agent-2')
45
+ .build();
46
+
47
+ // Exécution
48
+ const result = await pipeline.execute(input, agentsMap);
49
+ ```
50
+
51
+ ### Configuration
52
+
53
+ ```typescript
54
+ const pipeline = PipelineBuilder.create()
55
+ .withName('Analysis Pipeline')
56
+ .withTimeout(60000)
57
+ .onStepComplete((step, results) => {
58
+ console.log(`Step ${step.name} completed with ${results.length} results`);
59
+ })
60
+ // ... ajouter des steps
61
+ .build();
62
+ ```
63
+
64
+ ## Patterns de Base
65
+
66
+ ### Chain Pattern
67
+
68
+ Exécution séquentielle où la sortie de chaque agent alimente l'entrée du suivant.
69
+
70
+ ```typescript
71
+ // Chaîne simple
72
+ const pipeline = PipelineBuilder.create()
73
+ .then('researcher') // Recherche d'informations
74
+ .then('analyzer') // Analyse les données
75
+ .then('summarizer') // Crée un résumé
76
+ .build();
77
+
78
+ // Chaîne avec noms
79
+ const pipeline = PipelineBuilder.create()
80
+ .chain(['researcher', 'analyzer', 'summarizer'], 'analysis-chain')
81
+ .build();
82
+ ```
83
+
84
+ **Cas d'usage:**
85
+
86
+ - Processing étape par étape
87
+ - Raffinement itératif
88
+ - Pipeline de transformation
89
+
90
+ ### Scatter-Gather Pattern
91
+
92
+ Exécution parallèle de plusieurs agents avec agrégation des résultats.
93
+
94
+ ```typescript
95
+ import { Strategies } from 'societyai';
96
+
97
+ // Scatter to multiple agents
98
+ const pipeline = PipelineBuilder.create()
99
+ .scatter(['expert-1', 'expert-2', 'expert-3'])
100
+ .gather(Strategies.consensus(0.7))
101
+ .build();
102
+
103
+ // Convenience method
104
+ const pipeline = PipelineBuilder.create()
105
+ .scatterGather(['analyst-1', 'analyst-2', 'analyst-3'], Strategies.merge())
106
+ .build();
107
+ ```
108
+
109
+ **Cas d'usage:**
110
+
111
+ - Analyse multi-perspective
112
+ - Validation par consensus
113
+ - Parallélisation de tâches
114
+
115
+ ### Router Pattern
116
+
117
+ Routage dynamique vers un agent approprié basé sur l'entrée ou le contexte.
118
+
119
+ ```typescript
120
+ // Router avec fonction personnalisée
121
+ const pipeline = PipelineBuilder.create()
122
+ .route(['technical-expert', 'business-expert', 'legal-expert'], (input, ctx) => {
123
+ if (input.includes('legal')) return 'legal-expert';
124
+ if (input.includes('technical')) return 'technical-expert';
125
+ return 'business-expert';
126
+ })
127
+ .build();
128
+
129
+ // Router par contenu
130
+ const pipeline = PipelineBuilder.create()
131
+ .routeByContent(
132
+ [
133
+ { match: /bug|error|crash/, agentId: 'bug-fixer' },
134
+ { match: /feature|enhancement/, agentId: 'feature-developer' },
135
+ { match: /documentation/, agentId: 'doc-writer' },
136
+ ],
137
+ 'general-agent' // Agent par défaut
138
+ )
139
+ .build();
140
+ ```
141
+
142
+ **Cas d'usage:**
143
+
144
+ - Classification de requêtes
145
+ - Routage par expertise
146
+ - Triage automatique
147
+
148
+ ### Splitter Pattern
149
+
150
+ Division de l'entrée pour traitement parallèle de parties séparées.
151
+
152
+ ```typescript
153
+ // Split avec fonction personnalisée
154
+ const pipeline = PipelineBuilder.create()
155
+ .split('processor', (input) => {
156
+ // Diviser en paragraphes
157
+ return input.split('\n\n');
158
+ })
159
+ .gather(Strategies.concat('\n\n'))
160
+ .build();
161
+
162
+ // Split par délimiteur
163
+ const pipeline = PipelineBuilder.create()
164
+ .splitByDelimiter('analyzer', '\n---\n')
165
+ .gather(Strategies.merge())
166
+ .build();
167
+
168
+ // Split par lignes
169
+ const pipeline = PipelineBuilder.create()
170
+ .splitByLines('line-processor', {
171
+ chunkSize: 10, // Grouper par 10 lignes
172
+ skipEmpty: true,
173
+ })
174
+ .gather(Strategies.concat())
175
+ .build();
176
+ ```
177
+
178
+ **Cas d'usage:**
179
+
180
+ - Traitement de documents longs
181
+ - Analyse parallèle de sections
182
+ - Processing par batch
183
+
184
+ ## Patterns Avancés
185
+
186
+ ### Transform Pattern
187
+
188
+ Transformation de données entre étapes.
189
+
190
+ ```typescript
191
+ const pipeline = PipelineBuilder.create()
192
+ .then('analyzer')
193
+ .transform((result, ctx) => {
194
+ // Extraire seulement les données importantes
195
+ const data = JSON.parse(result);
196
+ return JSON.stringify(data.insights);
197
+ })
198
+ .then('reporter')
199
+ .build();
200
+ ```
201
+
202
+ ### Condition Pattern
203
+
204
+ Exécution conditionnelle basée sur le contexte.
205
+
206
+ ```typescript
207
+ const pipeline = PipelineBuilder.create()
208
+ .then('validator')
209
+ .condition(
210
+ (ctx) => {
211
+ // Vérifier si validation OK
212
+ return ctx.currentResult.includes('valid');
213
+ },
214
+ // Then branch (si true)
215
+ PipelineBuilder.create().then('approver').build(),
216
+ // Else branch (si false)
217
+ PipelineBuilder.create().then('reviewer').then('validator').build()
218
+ )
219
+ .build();
220
+ ```
221
+
222
+ ### Loop Pattern
223
+
224
+ Boucles avec condition de terminaison.
225
+
226
+ ```typescript
227
+ const pipeline = PipelineBuilder.create()
228
+ .loop(PipelineBuilder.create().then('generator').then('validator').build(), {
229
+ maxIterations: 5,
230
+ condition: (iteration, result, ctx) => {
231
+ // Continuer si pas validé
232
+ return !result.includes('approved');
233
+ },
234
+ })
235
+ .build();
236
+ ```
237
+
238
+ ### Aggregator Pattern
239
+
240
+ Agrégation de résultats avec stratégies personnalisées.
241
+
242
+ ```typescript
243
+ const pipeline = PipelineBuilder.create()
244
+ .scatter(['agent-1', 'agent-2', 'agent-3'])
245
+ .aggregate(Strategies.weightedVote([0.5, 0.3, 0.2]))
246
+ .build();
247
+
248
+ // Agrégation multi-niveau
249
+ const pipeline = PipelineBuilder.create()
250
+ .scatter(['group-1-a', 'group-1-b'])
251
+ .gather(Strategies.merge())
252
+ .scatter(['group-2-a', 'group-2-b'])
253
+ .gather(Strategies.concat())
254
+ .aggregate(Strategies.bestOf())
255
+ .build();
256
+ ```
257
+
258
+ ### Saga Pattern
259
+
260
+ Transaction distribuée avec compensation en cas d'échec.
261
+
262
+ ```typescript
263
+ const pipeline = PipelineBuilder.create()
264
+ .saga({
265
+ steps: [
266
+ {
267
+ agentId: 'reserve-inventory',
268
+ compensate: 'release-inventory',
269
+ },
270
+ {
271
+ agentId: 'charge-payment',
272
+ compensate: 'refund-payment',
273
+ },
274
+ {
275
+ agentId: 'ship-order',
276
+ compensate: 'cancel-shipment',
277
+ },
278
+ ],
279
+ onFailure: 'compensate-all', // ou 'compensate-previous'
280
+ })
281
+ .build();
282
+ ```
283
+
284
+ ### Circuit Breaker Pattern
285
+
286
+ Protection contre les défaillances en cascade.
287
+
288
+ ```typescript
289
+ const pipeline = PipelineBuilder.create()
290
+ .circuitBreaker({
291
+ agentId: 'external-api-agent',
292
+ failureThreshold: 5,
293
+ timeout: 10000,
294
+ resetTimeout: 60000,
295
+ fallback: 'cached-agent', // Agent de secours
296
+ })
297
+ .build();
298
+ ```
299
+
300
+ ## Built-in Pipelines
301
+
302
+ ### Pipelines Pré-construits
303
+
304
+ ```typescript
305
+ import { Pipelines } from 'societyai';
306
+
307
+ // Multi-perspective analysis
308
+ const pipeline = Pipelines.multiPerspective(
309
+ ['analyst-1', 'analyst-2', 'analyst-3'],
310
+ Strategies.consensus(0.6)
311
+ );
312
+
313
+ // Iterative refinement
314
+ const pipeline = Pipelines.iterativeRefinement('generator', 'critic', { maxIterations: 3 });
315
+
316
+ // Debate pattern
317
+ const pipeline = Pipelines.debate(['pro-agent', 'con-agent'], 'judge-agent', { rounds: 3 });
318
+
319
+ // Map-reduce
320
+ const pipeline = Pipelines.mapReduce('mapper', 'reducer', {
321
+ splitter: (input) => input.split('\n'),
322
+ aggregator: Strategies.concat('\n'),
323
+ });
324
+
325
+ // Hierarchical processing
326
+ const pipeline = Pipelines.hierarchical([
327
+ ['worker-1', 'worker-2', 'worker-3'], // Niveau 1
328
+ ['supervisor-1', 'supervisor-2'], // Niveau 2
329
+ ['manager'], // Niveau 3
330
+ ]);
331
+ ```
332
+
333
+ ## Composition de Pipelines
334
+
335
+ ### Combiner des Pipelines
336
+
337
+ ```typescript
338
+ import { composePipelines, parallelPipelines } from 'societyai';
339
+
340
+ // Exécution séquentielle de pipelines
341
+ const composed = composePipelines([pipeline1, pipeline2, pipeline3]);
342
+
343
+ // Exécution parallèle de pipelines
344
+ const parallel = parallelPipelines([pipeline1, pipeline2, pipeline3], Strategies.merge());
345
+
346
+ // Imbrication
347
+ const nested = PipelineBuilder.create()
348
+ .then('preprocessor')
349
+ .pipeline(subPipeline) // Pipeline imbriqué
350
+ .then('postprocessor')
351
+ .build();
352
+ ```
353
+
354
+ ### Pipelines Réutilisables
355
+
356
+ ```typescript
357
+ // Créer des factories de pipelines
358
+ function createValidationPipeline(validatorId: string, maxRetries: number) {
359
+ return PipelineBuilder.create()
360
+ .loop(PipelineBuilder.create().then('generator').then(validatorId).build(), {
361
+ maxIterations: maxRetries,
362
+ })
363
+ .build();
364
+ }
365
+
366
+ // Utiliser
367
+ const pipeline1 = createValidationPipeline('strict-validator', 5);
368
+ const pipeline2 = createValidationPipeline('lenient-validator', 3);
369
+ ```
370
+
371
+ ## Patterns Pré-configurés
372
+
373
+ ### Self-Correction Pattern
374
+
375
+ ```typescript
376
+ import { PipelinePatterns } from 'societyai';
377
+
378
+ const pipeline = PipelinePatterns.selfCorrection(
379
+ 'content-generator',
380
+ 'quality-validator',
381
+ 3 // max retries
382
+ );
383
+
384
+ // Utilisation
385
+ const result = await pipeline.execute('Generate a blog post about TypeScript', agents);
386
+ ```
387
+
388
+ **Comment ça marche:**
389
+
390
+ 1. Le générateur crée du contenu
391
+ 2. Le validateur vérifie la qualité
392
+ 3. Si pas valide, le feedback est renvoyé au générateur
393
+ 4. Répète jusqu'à validation ou max retries
394
+
395
+ ### Multi-Perspective Debate Pattern
396
+
397
+ ```typescript
398
+ const pipeline = PipelinePatterns.multiPerspectiveDebate(
399
+ 'pro-argument-agent',
400
+ 'con-argument-agent',
401
+ 'neutral-judge',
402
+ 3 // rounds of debate
403
+ );
404
+
405
+ // Utilisation
406
+ const result = await pipeline.execute('Should we adopt microservices architecture?', agents);
407
+ ```
408
+
409
+ **Comment ça marche:**
410
+
411
+ 1. Agent Pro présente ses arguments
412
+ 2. Agent Con présente ses contre-arguments
413
+ 3. Répète pour N rounds
414
+ 4. Juge synthétise la conclusion finale
415
+
416
+ ### Hierarchical Review Pattern
417
+
418
+ ```typescript
419
+ const pipeline = PipelinePatterns.hierarchicalReview([
420
+ ['junior-reviewer-1', 'junior-reviewer-2'],
421
+ ['senior-reviewer'],
422
+ ['chief-editor'],
423
+ ]);
424
+ ```
425
+
426
+ ### Ensemble Pattern
427
+
428
+ ```typescript
429
+ const pipeline = PipelinePatterns.ensemble(['model-1', 'model-2', 'model-3'], Strategies.voting(), {
430
+ minAgreement: 0.6,
431
+ });
432
+ ```
433
+
434
+ ## Exemples Complets
435
+
436
+ ### Exemple 1: Pipeline de Traitement de Document
437
+
438
+ ```typescript
439
+ import { PipelineBuilder, Strategies, Society } from 'societyai';
440
+
441
+ // Créer le pipeline
442
+ const documentPipeline = PipelineBuilder.create('document-analysis')
443
+ .withTimeout(120000) // 2 minutes
444
+
445
+ // 1. Prétraitement
446
+ .then('preprocessor')
447
+
448
+ // 2. Split par sections
449
+ .split('section-analyzer', (doc) => doc.split(/\n## /g))
450
+
451
+ // 3. Analyse parallèle des sections
452
+ .gather(Strategies.merge())
453
+
454
+ // 4. Router vers spécialistes
455
+ .route(['technical-expert', 'business-expert', 'legal-expert'], (result, ctx) => {
456
+ if (result.includes('technical')) return 'technical-expert';
457
+ if (result.includes('business')) return 'business-expert';
458
+ return 'legal-expert';
459
+ })
460
+
461
+ // 5. Validation
462
+ .then('quality-validator')
463
+
464
+ // 6. Formatting
465
+ .transform((result, ctx) => {
466
+ return formatReport(result, ctx.sharedData);
467
+ })
468
+
469
+ .onStepComplete((step, results) => {
470
+ console.log(`✅ ${step.name}: ${results.length} results`);
471
+ })
472
+
473
+ .build();
474
+
475
+ // Utiliser avec Society
476
+ const result = await Society.create()
477
+ .withName('Document Analyzer')
478
+ .addAgent(/* ... agents ... */)
479
+ .usePipeline(() => documentPipeline)
480
+ .execute(documentContent);
481
+ ```
482
+
483
+ ### Exemple 2: Pipeline de Génération de Code
484
+
485
+ ```typescript
486
+ const codePipeline = PipelineBuilder.create('code-generation')
487
+ // 1. Analyser les requirements
488
+ .then('requirements-analyzer')
489
+
490
+ // 2. Générer l'architecture
491
+ .then('architect')
492
+
493
+ // 3. Générer le code en parallèle
494
+ .scatter(['frontend-dev', 'backend-dev', 'database-dev'])
495
+ .gather(Strategies.merge())
496
+
497
+ // 4. Review et correction iterative
498
+ .loop(
499
+ PipelineBuilder.create()
500
+ .then('code-reviewer')
501
+ .condition(
502
+ (ctx) => ctx.currentResult.includes('approved'),
503
+ PipelineBuilder.create().build(), // Approuvé - sortir
504
+ PipelineBuilder.create() // Pas approuvé - corriger
505
+ .then('code-fixer')
506
+ .build()
507
+ )
508
+ .build(),
509
+ { maxIterations: 3 }
510
+ )
511
+
512
+ // 5. Génération tests
513
+ .then('test-generator')
514
+
515
+ // 6. Documentation
516
+ .then('doc-generator')
517
+
518
+ .build();
519
+ ```
520
+
521
+ ### Exemple 3: Pipeline de Customer Support
522
+
523
+ ```typescript
524
+ const supportPipeline = PipelineBuilder.create('customer-support')
525
+ // 1. Classification de la requête
526
+ .routeByContent(
527
+ [
528
+ { match: /billing|payment|invoice/, agentId: 'billing-agent' },
529
+ { match: /technical|bug|error/, agentId: 'technical-agent' },
530
+ { match: /account|password|login/, agentId: 'account-agent' },
531
+ { match: /cancel|refund/, agentId: 'retention-agent' },
532
+ ],
533
+ 'general-support'
534
+ )
535
+
536
+ // 2. Traitement spécialisé
537
+ .condition(
538
+ (ctx) => ctx.sharedData.get('needsEscalation'),
539
+ // Escalation branch
540
+ PipelineBuilder.create().then('senior-support').then('manager-review').build(),
541
+ // Resolution branch
542
+ PipelineBuilder.create().then('resolution-agent').build()
543
+ )
544
+
545
+ // 3. Génération de réponse
546
+ .then('response-generator')
547
+
548
+ // 4. Quality check
549
+ .then('quality-checker')
550
+
551
+ // 5. Sentiment analysis
552
+ .then('sentiment-analyzer')
553
+
554
+ .build();
555
+ ```
556
+
557
+ ### Exemple 4: Pipeline de Recherche Académique
558
+
559
+ ```typescript
560
+ const researchPipeline = PipelineBuilder.create('academic-research')
561
+ // 1. Recherche parallèle dans différentes sources
562
+ .scatterGather(['pubmed-searcher', 'arxiv-searcher', 'scholar-searcher'], Strategies.merge())
563
+
564
+ // 2. Filtrage et déduplication
565
+ .transform((results, ctx) => {
566
+ const papers = JSON.parse(results);
567
+ const unique = deduplicatePapers(papers);
568
+ const filtered = filterByRelevance(unique, ctx.input);
569
+ return JSON.stringify(filtered);
570
+ })
571
+
572
+ // 3. Analyse détaillée en parallèle
573
+ .splitByDelimiter('paper-analyzer', /\n---\n/)
574
+ .gather(Strategies.concat('\n\n'))
575
+
576
+ // 4. Synthèse multi-perspective
577
+ .scatterGather(
578
+ ['methodology-analyst', 'results-analyst', 'implications-analyst'],
579
+ Strategies.concat('\n\n## ')
580
+ )
581
+
582
+ // 5. Génération de rapport
583
+ .then('report-generator')
584
+
585
+ // 6. Citation formatting
586
+ .then('citation-formatter')
587
+
588
+ // 7. Peer review
589
+ .scatterGather(['reviewer-1', 'reviewer-2', 'reviewer-3'], Strategies.consensus(0.67))
590
+
591
+ .build();
592
+ ```
593
+
594
+ ### Exemple 5: Pipeline avec Circuit Breaker
595
+
596
+ ```typescript
597
+ const robustPipeline = PipelineBuilder.create('robust-processing')
598
+ // Agent avec protection
599
+ .circuitBreaker({
600
+ agentId: 'external-api-agent',
601
+ failureThreshold: 3,
602
+ timeout: 5000,
603
+ resetTimeout: 30000,
604
+ fallback: 'cached-agent',
605
+ onOpen: () => {
606
+ console.warn('Circuit opened - using fallback');
607
+ metrics.increment('circuit_breaker.opened');
608
+ },
609
+ onClose: () => {
610
+ console.log('Circuit closed - back to normal');
611
+ metrics.increment('circuit_breaker.closed');
612
+ },
613
+ })
614
+
615
+ // Traitement normal
616
+ .then('processor')
617
+
618
+ .build();
619
+ ```
620
+
621
+ ## Bonnes Pratiques
622
+
623
+ ### 1. Nommer les Steps
624
+
625
+ ```typescript
626
+ // ✅ Bon - noms descriptifs
627
+ .chain(['researcher', 'analyzer'], 'research-phase')
628
+ .scatter(['expert-1', 'expert-2'], 'expert-review')
629
+
630
+ // ❌ Mauvais - pas de noms
631
+ .chain(['agent1', 'agent2'])
632
+ ```
633
+
634
+ ### 2. Gestion des Timeouts
635
+
636
+ ```typescript
637
+ // ✅ Bon - timeout adapté
638
+ const pipeline = PipelineBuilder.create()
639
+ .withTimeout(60000) // 1 minute pour pipeline complet
640
+ .then('quick-agent')
641
+ .build();
642
+
643
+ // ✅ Bon - timeout par agent si nécessaire
644
+ const agent = AgentBuilder.create()
645
+ .withId('slow-agent')
646
+ .withRetry({
647
+ maxRetries: 3,
648
+ timeout: 30000, // 30s par tentative
649
+ })
650
+ .build();
651
+ ```
652
+
653
+ ### 3. Stratégies d'Agrégation Appropriées
654
+
655
+ ```typescript
656
+ // ✅ Bon - stratégie adaptée au cas d'usage
657
+ .scatterGather(
658
+ ['fact-checker-1', 'fact-checker-2'],
659
+ Strategies.consensus(0.8) // Haute conf pour facts
660
+ )
661
+
662
+ // ✅ Bon - concat pour perspectives
663
+ .scatterGather(
664
+ ['analyst-1', 'analyst-2'],
665
+ Strategies.concat('\n\n')
666
+ )
667
+ ```
668
+
669
+ ### 4. Error Handling
670
+
671
+ ```typescript
672
+ // ✅ Bon - gestion d'erreurs
673
+ const pipeline = PipelineBuilder.create()
674
+ .onStepComplete((step, results) => {
675
+ const failures = results.filter((r) => !r.success);
676
+ if (failures.length > 0) {
677
+ logger.warn(`Step ${step.name} had ${failures.length} failures`);
678
+ }
679
+ })
680
+ .build();
681
+ ```
682
+
683
+ ### 5. Context Sharing
684
+
685
+ ```typescript
686
+ // ✅ Bon - utiliser sharedData pour communication
687
+ .transform((result, ctx) => {
688
+ // Stocker des données pour les steps suivants
689
+ ctx.sharedData.set('analysis-results', JSON.parse(result));
690
+ return result;
691
+ })
692
+
693
+ .route(['agent-a', 'agent-b'], (input, ctx) => {
694
+ // Utiliser les données partagées
695
+ const analysis = ctx.sharedData.get('analysis-results');
696
+ return analysis.complexity > 0.5 ? 'agent-a' : 'agent-b';
697
+ })
698
+ ```
699
+
700
+ ## API Reference
701
+
702
+ ### `PipelineBuilder`
703
+
704
+ **Méthodes de construction:**
705
+
706
+ - `static create(name?: string): PipelineBuilder`
707
+ - `withName(name: string): this`
708
+ - `withTimeout(ms: number): this`
709
+ - `onStepComplete(handler): this`
710
+
711
+ **Patterns:**
712
+
713
+ - `then(agentId: string, name?: string): this`
714
+ - `chain(agentIds: string[], name?: string): this`
715
+ - `scatter(agentIds: string[], name?: string): this`
716
+ - `gather(strategy: AggregationStrategy, name?: string): this`
717
+ - `scatterGather(agentIds: string[], strategy: AggregationStrategy, name?: string): this`
718
+ - `route(agentIds: string[], router: Function, name?: string): this`
719
+ - `routeByContent(routes: RouteConfig[], defaultId: string, name?: string): this`
720
+ - `split(agentId: string, splitter: Function, name?: string): this`
721
+ - `splitByDelimiter(agentId: string, delimiter: string | RegExp, name?: string): this`
722
+ - `transform(transformer: Function, name?: string): this`
723
+ - `condition(condition: Function, thenPipeline: Pipeline, elsePipeline?: Pipeline): this`
724
+ - `loop(pipeline: Pipeline, config: LoopConfig): this`
725
+ - `aggregate(strategy: AggregationStrategy, name?: string): this`
726
+ - `saga(config: SagaConfig): this`
727
+ - `circuitBreaker(config: CircuitBreakerConfig): this`
728
+ - `pipeline(nested: Pipeline, name?: string): this`
729
+ - `build(): Pipeline`
730
+
731
+ ### `Pipelines`
732
+
733
+ **Built-in Pipelines:**
734
+
735
+ - `static multiPerspective(agentIds: string[], strategy: AggregationStrategy): Pipeline`
736
+ - `static iterativeRefinement(generatorId: string, criticId: string, config): Pipeline`
737
+ - `static debate(debaterIds: string[], judgeId: string, config): Pipeline`
738
+ - `static mapReduce(mapperId: string, reducerId: string, config): Pipeline`
739
+ - `static hierarchical(levels: string[][]): Pipeline`
740
+
741
+ ### `PipelinePatterns`
742
+
743
+ **Pre-configured Patterns:**
744
+
745
+ - `static selfCorrection(generatorId: string, validatorId: string, maxRetries: number): Pipeline`
746
+ - `static multiPerspectiveDebate(agentAId: string, agentBId: string, judgeId: string, rounds: number): Pipeline`
747
+
748
+ ### `Pipeline` Interface
749
+
750
+ **Méthodes:**
751
+
752
+ - `execute(input: string, agents: Map<string, AgentConfig>, signal?: AbortSignal): Promise<PipelineResult>`
753
+ - `getSteps(): readonly PipelineStep[]`
754
+ - `getName(): string`
755
+
756
+ ## Voir Aussi
757
+
758
+ - [Workflows](./workflows.md) - Patterns de workflow
759
+ - [Graph Execution](./graph-execution.md) - Workflows basés sur graphes
760
+ - [Strategies](./aggregation-strategies.md) - Stratégies d'agrégation
761
+ - [Advanced Patterns](./advanced.md) - Patterns avancés