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
package/README.md ADDED
@@ -0,0 +1,879 @@
1
+ # SocietyAI
2
+
3
+ [![npm version](https://img.shields.io/npm/v/societyai.svg)](https://www.npmjs.com/package/societyai)
4
+ [![License](https://img.shields.io/badge/License-MIT-blue.svg)](https://opensource.org/licenses/MIT)
5
+ [![TypeScript](https://img.shields.io/badge/TypeScript-5.3-blue.svg)](https://www.typescriptlang.org/)
6
+ [![Zero Dependencies](https://img.shields.io/badge/dependencies-0-brightgreen.svg)](package.json)
7
+
8
+ **SocietyAI** is a powerful TypeScript library for creating collaborative multi-agent AI systems. Build sophisticated workflows where AI agents with different roles and capabilities work together to solve complex problems, analyze information from multiple perspectives, and generate comprehensive responses.
9
+
10
+ The library is **fully configurable**, **model-agnostic**, and **domain-independent** - use it for software development, research, content creation, business analysis, or any domain where multiple perspectives add value.
11
+
12
+ > Status: Pre-release. The first public release will be `0.0.1` and the API may change.
13
+
14
+ ## ๐ŸŽฏ Design Principles
15
+
16
+ - **Model-Agnostic**: Works with any AI model (OpenAI, Anthropic, Google, local models, or custom APIs)
17
+ - **Domain-Independent**: No hardcoded prompts or business logic - fully configurable for any use case
18
+ - **Zero Runtime Dependencies**: Pure TypeScript with no external runtime dependencies
19
+ - **Fluent Builder API**: Intuitive chainable interfaces for configuring agents, roles, and workflows
20
+
21
+ ## โœจ Features
22
+
23
+ ### Core Capabilities
24
+
25
+ - **๐Ÿค– Configurable Multi-Agent System**: Define custom roles, behaviors, capabilities, and constraints for each agent
26
+ - **๐Ÿ”„ Flexible Workflow Engine**: Sequential, parallel, collaborative, and conditional execution patterns
27
+ - **๐ŸŽฏ Graph-Based Execution**: DAG/Cyclic graphs with conditional branching and loops for complex workflows
28
+ - **๐Ÿ› ๏ธ Tool Calling System**: Enable agents to interact with external functions and APIs with JSON Schema validation
29
+ - **๐Ÿง  Multi-Level Memory**: Intelligent context management with short-term, long-term, and entity memory
30
+ - **๐Ÿ’ฌ Inter-Agent Communication**: Built-in message bus for agent-to-agent information exchange
31
+ - **๐Ÿ”Œ Model-Agnostic**: Works with any AI model - OpenAI, Anthropic, Google, local models, or custom APIs
32
+ - **๐Ÿ—๏ธ Builder Pattern API**: Intuitive fluent interfaces for creating agents, roles, and workflows
33
+ - **โšก High Performance**: Worker pool for parallelization, timeout support, and operation cancellation
34
+ - **๐Ÿ›ก๏ธ Robust Error Handling**: Automatic retry with exponential backoff and comprehensive error types
35
+ - **๐Ÿ“Š Full Observability**: Logging system and observer pattern for monitoring and debugging
36
+ - **๐ŸŽฏ Type-Safe**: Written in TypeScript with complete type definitions
37
+ - **๐Ÿ“ฆ Zero Dependencies**: No external runtime dependencies (only dev dependencies for testing)
38
+
39
+ ### Advanced Features
40
+
41
+ #### Builder & Orchestration
42
+
43
+ - **๐Ÿ—๏ธ Fluent Society Builder**: `Society.create()` entry point with chainable methods
44
+ - **๐Ÿ”€ Pipeline Patterns**: Chain, Scatter-Gather, Router, Splitter, Map-Reduce, Saga patterns
45
+ - **๐Ÿ“Š SocietyGraph**: Graph-based execution with 8 node types (START, END, AGENT, PARALLEL, AGGREGATE, CONDITION, TRANSFORM, LOOP)
46
+ - **๐ŸŽจ Pre-built Patterns**: Self-correction, multi-perspective debate, hierarchical review, ensemble patterns
47
+
48
+ #### Data & State Management
49
+
50
+ - **๐Ÿ”ง Tool Registry**: Register and execute tools with JSON Schema validation and error handling
51
+ - **๐Ÿ’พ Memory System**: ShortTermMemory with auto-summarization, LongTermMemory with RAG, EntityMemory for facts tracking
52
+ - **๐Ÿ—‚๏ธ Context System**: Type-safe context injection with tokens, providers, scopes (global, workflow, step, agent)
53
+ - **โœ… Structured Output**: JSON Schema validation with automatic retry and error feedback
54
+ - **๐Ÿ“ก Event System**: Typed events for lifecycle (workflow, step, agent), progress tracking, and debugging
55
+
56
+ #### Performance & Reliability
57
+
58
+ - **๐Ÿ“ˆ Metrics & Observability**: Token counting, cost estimation, performance profiling, OpenTelemetry export support
59
+ - **๐Ÿ”Œ Middleware System**: Composable interceptors for logging, caching, rate limiting, retry, circuit breaker, timeout
60
+ - **๐Ÿ“Š Aggregation Strategies**: Consensus, majority vote, weighted vote, best-of, ranking, unanimous, custom reducers
61
+ - **๐Ÿ”„ Retry Mechanisms**: Exponential backoff, conditional retry, circuit breaker protection
62
+ - **โฑ๏ธ Timeout & Cancellation**: AbortSignal support, configurable timeouts per agent or workflow
63
+
64
+ ## ๐Ÿ“ฆ Installation
65
+
66
+ ```bash
67
+ npm install societyai
68
+ ```
69
+
70
+ ## ๐Ÿš€ Quick Start
71
+
72
+ ### Basic Example
73
+
74
+ ```typescript
75
+ import {
76
+ RoleBuilder,
77
+ AgentBuilder,
78
+ StepBuilder,
79
+ WorkflowConfigBuilder,
80
+ DefaultWorkflowExecutor,
81
+ StandardModelBase,
82
+ } from 'societyai';
83
+
84
+ // 1. Create your AI model (connect to any AI API)
85
+ class MyAIModel extends StandardModelBase {
86
+ constructor() {
87
+ super({ name: 'MyModel' }, async (prompt) => {
88
+ // Connect to your AI API here (OpenAI, Anthropic, etc.)
89
+ const response = await fetch('https://api.example.com/ai', {
90
+ method: 'POST',
91
+ body: JSON.stringify({ prompt }),
92
+ });
93
+ return await response.text();
94
+ });
95
+ }
96
+ }
97
+
98
+ // 2. Define agent roles
99
+ const analyst = RoleBuilder.create()
100
+ .withId('analyst')
101
+ .withName('Data Analyst')
102
+ .withSystemPrompt(
103
+ 'You are a data analyst. Examine information objectively and identify patterns.'
104
+ )
105
+ .withCapabilities(['data-analysis', 'pattern-recognition'])
106
+ .build();
107
+
108
+ const reviewer = RoleBuilder.create()
109
+ .withId('reviewer')
110
+ .withName('Critical Reviewer')
111
+ .withSystemPrompt('You are a critical reviewer. Challenge assumptions and ensure quality.')
112
+ .build();
113
+
114
+ // 3. Create agents with roles and models
115
+ const model = new MyAIModel();
116
+
117
+ const agents = [
118
+ AgentBuilder.create().withId('analyst-1').withRole(analyst).withModel(model).build(),
119
+
120
+ AgentBuilder.create().withId('reviewer-1').withRole(reviewer).withModel(model).build(),
121
+ ];
122
+
123
+ // 4. Define workflow steps
124
+ const workflow = WorkflowConfigBuilder.create()
125
+ .withId('analysis-workflow')
126
+ .withName('Analysis Workflow')
127
+ .addAgents(agents)
128
+ .addStep(
129
+ StepBuilder.create()
130
+ .withId('analysis')
131
+ .withName('Initial Analysis')
132
+ .withAgents(['analyst-1'])
133
+ .withExecutionType('sequential')
134
+ .withInstructions('Analyze the input thoroughly.')
135
+ .build()
136
+ )
137
+ .addStep(
138
+ StepBuilder.create()
139
+ .withId('review')
140
+ .withName('Quality Review')
141
+ .withAgents(['reviewer-1'])
142
+ .withExecutionType('sequential')
143
+ .withInstructions('Review and validate the analysis.')
144
+ .build()
145
+ )
146
+ .build();
147
+
148
+ // 5. Execute the workflow
149
+ const executor = new DefaultWorkflowExecutor();
150
+ const result = await executor.execute(workflow, 'Analyze market trends for Q4 2024');
151
+
152
+ console.log(result.output);
153
+ console.log(`Completed in ${result.duration}ms`);
154
+ ```
155
+
156
+ ## ๐Ÿ†• Fluent Society Builder
157
+
158
+ ### Society Builder API
159
+
160
+ The new `Society.create()` provides a simpler, more intuitive way to create agent societies:
161
+
162
+ ```typescript
163
+ import { Society, Strategies } from 'societyai';
164
+
165
+ // Create and execute a society in one fluent chain
166
+ const result = await Society.create()
167
+ .withName('Analysis Team')
168
+ .addAgent((a) =>
169
+ a
170
+ .withId('analyst')
171
+ .withRole((r) =>
172
+ r
173
+ .withSystemPrompt('You are a data analyst. Examine patterns objectively.')
174
+ .withCapabilities(['analysis', 'pattern-recognition'])
175
+ )
176
+ .withModel(model)
177
+ )
178
+ .addAgent((a) =>
179
+ a
180
+ .withId('critic')
181
+ .withRole((r) => r.withSystemPrompt('You are a critical reviewer. Challenge assumptions.'))
182
+ .withModel(model)
183
+ )
184
+ .scatterGather(Strategies.consensus(0.7).aggregate)
185
+ .execute('Analyze the impact of AI on healthcare');
186
+
187
+ console.log(result.output);
188
+ ```
189
+
190
+ ### Pipeline Patterns
191
+
192
+ Use pre-built execution patterns for common workflows:
193
+
194
+ ```typescript
195
+ import { Society, Pipelines, Strategies } from 'societyai';
196
+
197
+ // Use a pre-built pipeline pattern
198
+ const society = Society.create()
199
+ .withName('Content Pipeline')
200
+ .useAgents([writer, editor, reviewer])
201
+ .usePipeline(
202
+ (p) =>
203
+ p
204
+ .then('writer') // First, writer creates draft
205
+ .then('editor') // Then, editor improves it
206
+ .scatterGather(['reviewer', 'editor'], Strategies.concat()) // Both review
207
+ );
208
+
209
+ const result = await society.execute('Write a blog post about TypeScript');
210
+ ```
211
+
212
+ Available patterns:
213
+
214
+ - `Pipelines.chain('a', 'b', 'c')` - Sequential execution
215
+ - `Pipelines.scatterGather(['a', 'b'], strategy)` - Parallel with aggregation
216
+ - `Pipelines.review('drafter', 'reviewer')` - Draft and review pattern
217
+ - `Pipelines.consensus(['a', 'b', 'c'], 'finalizer', 0.6)` - Consensus building
218
+ - `Pipelines.debate('agent1', 'agent2', 'judge', rounds)` - Debate pattern
219
+ - `Pipelines.iterativeRefinement('agent', iterations)` - Iterative improvement
220
+
221
+ ### Aggregation Strategies
222
+
223
+ Combine results from multiple agents:
224
+
225
+ ```typescript
226
+ import { Strategies } from 'societyai';
227
+
228
+ // Basic strategies
229
+ Strategies.concat('\n\n'); // Concatenate all results
230
+ Strategies.first(); // First successful result
231
+ Strategies.last(); // Last successful result
232
+ Strategies.longest(); // Longest result
233
+ Strategies.shortest(); // Shortest result
234
+
235
+ // Voting strategies
236
+ Strategies.majority(); // Most common response
237
+ Strategies.consensus(0.7); // Requires 70% agreement
238
+ Strategies.weighted(weights); // Weighted by agent
239
+ Strategies.best(scorer); // Best by custom score
240
+
241
+ // Composition
242
+ Strategies.compose(s1, s2, s3); // Chain strategies
243
+ Strategies.fallback(primary, backup);
244
+ ```
245
+
246
+ ### Middleware System
247
+
248
+ Add cross-cutting concerns with composable middleware:
249
+
250
+ ```typescript
251
+ import { MiddlewareChain, Middlewares } from 'societyai';
252
+
253
+ // Create a middleware chain
254
+ const middleware = MiddlewareChain.create()
255
+ .use(Middlewares.logging({ logInput: true, logOutput: true }))
256
+ .use(Middlewares.timing())
257
+ .use(Middlewares.retry({ maxAttempts: 3, delay: 1000 }))
258
+ .use(Middlewares.cache({ ttl: 60000 }))
259
+ .use(Middlewares.rateLimit({ maxRequests: 10, windowMs: 60000 }));
260
+
261
+ // Wrap your model with middleware
262
+ const enhancedModel = middleware.wrap(originalModel);
263
+ ```
264
+
265
+ Available middlewares:
266
+
267
+ - `Middlewares.logging(options)` - Log requests/responses
268
+ - `Middlewares.timing(onComplete)` - Measure duration
269
+ - `Middlewares.retry(options)` - Retry on failure
270
+ - `Middlewares.cache(options)` - Cache responses
271
+ - `Middlewares.rateLimit(options)` - Limit request rate
272
+ - `Middlewares.timeout(ms)` - Enforce timeout
273
+ - `Middlewares.circuitBreaker(options)` - Circuit breaker pattern
274
+ - `Middlewares.dedupe()` - Deduplicate concurrent requests
275
+
276
+ ### Context System
277
+
278
+ Type-safe state sharing between agents:
279
+
280
+ ```typescript
281
+ import { createContextToken, ContextProvider, CommonContexts } from 'societyai';
282
+
283
+ // Define custom context tokens
284
+ const UserContext = createContextToken<User>('user');
285
+ const ConfigContext = createContextToken<Config>('config', defaultConfig);
286
+
287
+ // Create provider
288
+ const context = ContextProvider.create()
289
+ .provide(UserContext, currentUser)
290
+ .provideFactory(ConfigContext, () => loadConfig())
291
+ .build();
292
+
293
+ // Access context
294
+ const user = context.get(UserContext);
295
+ const config = context.getOptional(ConfigContext);
296
+
297
+ // Use in society
298
+ const society = Society.create().withGlobalContext({ user, config }).addAgent(/* ... */).chain();
299
+ ```
300
+
301
+ ### Event System
302
+
303
+ Monitor execution with typed events:
304
+
305
+ ```typescript
306
+ import { createEventEmitter, createProgressTracker } from 'societyai';
307
+
308
+ const emitter = createEventEmitter();
309
+
310
+ // Subscribe to events
311
+ emitter.on('workflow:start', (e) => console.log('Started'));
312
+ emitter.on('agent:complete', (e) => console.log(`Agent done: ${e.agentId}`));
313
+ emitter.on('progress', (e) => updateUI(e.percent));
314
+
315
+ // Event types: workflow:start, workflow:complete, workflow:error
316
+ // step:start, step:complete, step:error
317
+ // agent:start, agent:complete, agent:error, agent:retry
318
+ // progress, message:sent, message:received, debug
319
+
320
+ // Use the observer in your society
321
+ const society = Society.create().withObserver(emitter.toObserver()).addAgent(/* ... */).chain();
322
+ ```
323
+
324
+ ## ๐Ÿ“š Key Concepts
325
+
326
+ ### Execution Types
327
+
328
+ | Type | Description | Use Case |
329
+ | --------------- | --------------------------------------------------- | ---------------------------------------- |
330
+ | `sequential` | Agents execute one after another in order | Pipeline processing, step-by-step tasks |
331
+ | `parallel` | All agents execute simultaneously | Independent analyses, speed optimization |
332
+ | `collaborative` | Agents exchange messages across multiple iterations | Discussions, consensus building |
333
+ | `conditional` | Step executes only if condition is met | Dynamic workflows, branching logic |
334
+
335
+ ### Architecture Overview
336
+
337
+ ```
338
+ โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
339
+ โ”‚ WorkflowConfig โ”‚
340
+ โ”‚ โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ” โ”‚
341
+ โ”‚ โ”‚ Agents (with Roles & Models) โ”‚ โ”‚
342
+ โ”‚ โ”œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ค โ”‚
343
+ โ”‚ โ”‚ Steps (Sequential/Parallel/Collaborative) โ”‚ โ”‚
344
+ โ”‚ โ”œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ค โ”‚
345
+ โ”‚ โ”‚ Communication Channels (MessageBus) โ”‚ โ”‚
346
+ โ”‚ โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜ โ”‚
347
+ โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜
348
+ โ”‚
349
+ โ–ผ
350
+ DefaultWorkflowExecutor
351
+ โ”‚
352
+ โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ผโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
353
+ โ–ผ โ–ผ โ–ผ
354
+ Agent 1 Agent 2 Agent 3
355
+ โ”‚ โ”‚ โ”‚
356
+ โ–ผ โ–ผ โ–ผ
357
+ AI Model AI Model AI Model
358
+ ```
359
+
360
+ ## ๐ŸŽฏ Common Use Cases
361
+
362
+ ### Software Development Team
363
+
364
+ ```typescript
365
+ const pmRole = RoleBuilder.create()
366
+ .withId('pm')
367
+ .withSystemPrompt('You organize and plan development tasks.')
368
+ .build();
369
+
370
+ const devRole = RoleBuilder.create()
371
+ .withId('dev')
372
+ .withSystemPrompt('You implement features following best practices.')
373
+ .build();
374
+
375
+ const qaRole = RoleBuilder.create()
376
+ .withId('qa')
377
+ .withSystemPrompt('You test implementations and find bugs.')
378
+ .build();
379
+
380
+ // Create workflow with parallel development
381
+ const devWorkflow = WorkflowConfigBuilder.create()
382
+ .addAgents([pmAgent, dev1Agent, dev2Agent, qaAgent])
383
+ .addStep(planningStep)
384
+ .addStep(parallelDevStep) // Both devs work simultaneously
385
+ .addStep(testingStep)
386
+ .build();
387
+ ```
388
+
389
+ ### Research & Analysis
390
+
391
+ ```typescript
392
+ const researchWorkflow = WorkflowConfigBuilder.create()
393
+ .addStep(
394
+ StepBuilder.create()
395
+ .withId('gather')
396
+ .withAgents(['researcher-1', 'researcher-2'])
397
+ .withExecutionType('parallel')
398
+ .build()
399
+ )
400
+ .addStep(
401
+ StepBuilder.create()
402
+ .withId('synthesize')
403
+ .withAgents(['synthesizer'])
404
+ .withExecutionType('sequential')
405
+ .build()
406
+ )
407
+ .build();
408
+ ```
409
+
410
+ ### Collaborative Discussion
411
+
412
+ ```typescript
413
+ const discussionStep = StepBuilder.create()
414
+ .withId('discussion')
415
+ .withAgents(['participant-1', 'participant-2', 'participant-3'])
416
+ .withExecutionType('collaborative')
417
+ .withMaxIterations(3) // Up to 3 rounds
418
+ .withCompletionCondition((results, iteration) => {
419
+ // Custom completion logic
420
+ return iteration >= 2 || consensusReached(results);
421
+ })
422
+ .build();
423
+ ```
424
+
425
+ ## ๐Ÿ”ง Advanced Features
426
+
427
+ ### Inter-Agent Communication
428
+
429
+ ```typescript
430
+ // Agents can communicate directly with each other
431
+ const agent1 = AgentBuilder.create()
432
+ .withId('agent-1')
433
+ .canCommunicateWith(['agent-2', 'agent-3'])
434
+ .build();
435
+
436
+ // Messages are automatically passed through MessageBus
437
+ // Agents can send requests, responses, and share data
438
+ ```
439
+
440
+ ### Custom Result Generators
441
+
442
+ ```typescript
443
+ WorkflowConfigBuilder.create()
444
+ .withFinalResultGenerator(async (stepResults, context) => {
445
+ // Custom logic to combine all step results
446
+ let summary = 'Executive Summary:\n';
447
+
448
+ for (const [stepId, results] of stepResults) {
449
+ summary += `\n${stepId}:\n`;
450
+ results.forEach((r) => {
451
+ if (r.success) {
452
+ summary += ` - ${r.agentId}: ${r.content.substring(0, 100)}...\n`;
453
+ }
454
+ });
455
+ }
456
+
457
+ return summary;
458
+ })
459
+ .build();
460
+ ```
461
+
462
+ ### Lifecycle Hooks
463
+
464
+ ```typescript
465
+ WorkflowConfigBuilder.create()
466
+ .onBeforeStep(async (step, context) => {
467
+ console.log(`Starting: ${step.name}`);
468
+ // Inject dynamic data, log metrics, etc.
469
+ })
470
+ .onAfterStep(async (step, results, context) => {
471
+ console.log(`Completed: ${step.name}`);
472
+ // Store results, trigger notifications, etc.
473
+ })
474
+ .build();
475
+ ```
476
+
477
+ ### Observability
478
+
479
+ ```typescript
480
+ const observer: SocietyObserver = {
481
+ onSocietyStart(prompt, agentCount) {
482
+ console.log(`Starting with ${agentCount} agents`);
483
+ },
484
+ onAgentStart(agentId, modelName, prompt) {
485
+ console.log(`Agent ${agentId} (${modelName}) started`);
486
+ },
487
+ onAgentComplete(agentId, modelName, result) {
488
+ console.log(`Agent ${agentId} completed successfully`);
489
+ },
490
+ onAgentError(agentId, modelName, error) {
491
+ console.error(`Agent ${agentId} failed:`, error);
492
+ },
493
+ onPhaseStart(phase) {
494
+ console.log(`Phase: ${phase}`);
495
+ },
496
+ onPhaseComplete(phase) {
497
+ console.log(`Phase ${phase} completed`);
498
+ },
499
+ onSocietyComplete(result) {
500
+ console.log('Workflow complete');
501
+ },
502
+ };
503
+
504
+ const executor = new DefaultWorkflowExecutor(observer);
505
+ ```
506
+
507
+ ### Timeout & Cancellation
508
+
509
+ ```typescript
510
+ // Create an abort controller for cancellation
511
+ const controller = new AbortController();
512
+
513
+ // Set a timeout
514
+ setTimeout(() => controller.abort(), 30000); // 30 seconds
515
+
516
+ // Execute with cancellation support
517
+ try {
518
+ const result = await executor.execute(workflow, input, controller.signal);
519
+ } catch (error) {
520
+ if (error.name === 'AbortError') {
521
+ console.log('Operation cancelled');
522
+ }
523
+ }
524
+ ```
525
+
526
+ ### Error Handling
527
+
528
+ ```typescript
529
+ import {
530
+ SocietyError,
531
+ ProcessingFailedError,
532
+ TimeoutError,
533
+ InvalidConfigurationError,
534
+ } from 'societyai';
535
+
536
+ try {
537
+ const result = await executor.execute(workflow, input);
538
+ } catch (error) {
539
+ if (error instanceof ProcessingFailedError) {
540
+ console.error('AI model processing failed:', error.message);
541
+ } else if (error instanceof TimeoutError) {
542
+ console.error('Operation timed out');
543
+ } else if (error instanceof InvalidConfigurationError) {
544
+ console.error('Invalid workflow configuration:', error.message);
545
+ }
546
+ }
547
+ ```
548
+
549
+ ## ๐Ÿ”Œ Model Integration
550
+
551
+ ### OpenAI Integration
552
+
553
+ ```typescript
554
+ import OpenAI from 'openai';
555
+ import { StandardModelBase } from 'societyai';
556
+
557
+ class OpenAIModel extends StandardModelBase {
558
+ private client: OpenAI;
559
+
560
+ constructor(apiKey: string, model = 'gpt-4-turbo') {
561
+ const client = new OpenAI({ apiKey });
562
+
563
+ super({ name: model }, async (prompt) => {
564
+ const response = await client.chat.completions.create({
565
+ model,
566
+ messages: [{ role: 'user', content: String(prompt) }],
567
+ });
568
+ return response.choices[0].message.content || '';
569
+ });
570
+
571
+ this.client = client;
572
+ }
573
+ }
574
+ ```
575
+
576
+ ### Anthropic Integration
577
+
578
+ ```typescript
579
+ import Anthropic from '@anthropic-ai/sdk';
580
+ import { StandardModelBase } from 'societyai';
581
+
582
+ class ClaudeModel extends StandardModelBase {
583
+ private client: Anthropic;
584
+
585
+ constructor(apiKey: string, model = 'claude-3-5-sonnet-20241022') {
586
+ const client = new Anthropic({ apiKey });
587
+
588
+ super({ name: model }, async (prompt) => {
589
+ const response = await client.messages.create({
590
+ model,
591
+ max_tokens: 4096,
592
+ messages: [{ role: 'user', content: String(prompt) }],
593
+ });
594
+ return response.content[0].type === 'text' ? response.content[0].text : '';
595
+ });
596
+
597
+ this.client = client;
598
+ }
599
+ }
600
+ ```
601
+
602
+ ### Custom API Integration
603
+
604
+ ```typescript
605
+ class CustomAIModel extends StandardModelBase {
606
+ constructor(apiUrl: string, apiKey: string) {
607
+ super({ name: 'CustomModel' }, async (prompt, signal) => {
608
+ const response = await fetch(apiUrl, {
609
+ method: 'POST',
610
+ headers: {
611
+ Authorization: `Bearer ${apiKey}`,
612
+ 'Content-Type': 'application/json',
613
+ },
614
+ body: JSON.stringify({ prompt: String(prompt) }),
615
+ signal, // Support cancellation
616
+ });
617
+
618
+ if (!response.ok) {
619
+ throw new Error(`API error: ${response.statusText}`);
620
+ }
621
+
622
+ const data = await response.json();
623
+ return data.result;
624
+ });
625
+ }
626
+ }
627
+ ```
628
+
629
+ ## ๐Ÿ“– API Reference
630
+
631
+ ### Core Classes
632
+
633
+ #### `RoleBuilder`
634
+
635
+ Create agent roles with specific behaviors.
636
+
637
+ ```typescript
638
+ RoleBuilder.create()
639
+ .withId(id: string)
640
+ .withName(name: string)
641
+ .withSystemPrompt(prompt: string)
642
+ .withCapabilities(capabilities: string[])
643
+ .withConstraints(constraints: string[])
644
+ .withPromptTemplate(template: string)
645
+ .build(): AgentRole
646
+ ```
647
+
648
+ #### `AgentBuilder`
649
+
650
+ Configure individual agents.
651
+
652
+ ```typescript
653
+ AgentBuilder.create()
654
+ .withId(id: string)
655
+ .withName(name: string)
656
+ .withRole(role: AgentRole)
657
+ .withModel(model: AIModel)
658
+ .canCommunicateWith(agentIds: string[])
659
+ .withPriority(priority: number)
660
+ .withInitialContext(context: Record<string, unknown>)
661
+ .build(): AgentConfig
662
+ ```
663
+
664
+ #### `StepBuilder`
665
+
666
+ Define workflow steps.
667
+
668
+ ```typescript
669
+ StepBuilder.create()
670
+ .withId(id: string)
671
+ .withName(name: string)
672
+ .withAgents(agentIds: string[])
673
+ .withExecutionType(type: WorkflowStepExecutionType)
674
+ .withInstructions(instructions: string)
675
+ .withMaxIterations(max: number)
676
+ .withCompletionCondition(condition: Function)
677
+ .withCondition(condition: Function)
678
+ .build(): WorkflowStep
679
+ ```
680
+
681
+ #### `WorkflowConfigBuilder`
682
+
683
+ Build complete workflows.
684
+
685
+ ```typescript
686
+ WorkflowConfigBuilder.create()
687
+ .withId(id: string)
688
+ .withName(name: string)
689
+ .addAgent(agent: AgentConfig)
690
+ .addAgents(agents: AgentConfig[])
691
+ .addStep(step: WorkflowStep)
692
+ .withGlobalContext(context: Record<string, unknown>)
693
+ .onBeforeStep(handler: Function)
694
+ .onAfterStep(handler: Function)
695
+ .withFinalResultGenerator(generator: Function)
696
+ .build(): WorkflowConfig
697
+ ```
698
+
699
+ #### `DefaultWorkflowExecutor`
700
+
701
+ Execute workflows.
702
+
703
+ ```typescript
704
+ const executor = new DefaultWorkflowExecutor(observer?: SocietyObserver);
705
+
706
+ await executor.execute(
707
+ workflow: WorkflowConfig,
708
+ input: string,
709
+ signal?: AbortSignal
710
+ ): Promise<WorkflowResult>
711
+ ```
712
+
713
+ ### Key Interfaces
714
+
715
+ ```typescript
716
+ interface AgentRole {
717
+ id: string;
718
+ name: string;
719
+ systemPrompt: string;
720
+ capabilities?: string[];
721
+ constraints?: string[];
722
+ promptTemplate?: string;
723
+ }
724
+
725
+ interface WorkflowStep {
726
+ id: string;
727
+ name: string;
728
+ agentIds: string[];
729
+ executionType: 'sequential' | 'parallel' | 'collaborative' | 'conditional';
730
+ instructions?: string;
731
+ maxIterations?: number;
732
+ completionCondition?: (results: StepResult[], iteration: number) => boolean;
733
+ }
734
+
735
+ interface WorkflowResult {
736
+ success: boolean;
737
+ output: string;
738
+ stepResults: Map<string, StepResult[]>;
739
+ messages: AgentMessage[];
740
+ duration: number;
741
+ errors?: Error[];
742
+ }
743
+
744
+ interface StepResult {
745
+ agentId: string;
746
+ stepId: string;
747
+ content: string;
748
+ success: boolean;
749
+ timestamp: number;
750
+ error?: Error;
751
+ }
752
+ ```
753
+
754
+ ## ๐Ÿ“˜ Documentation
755
+
756
+ ### Getting Started
757
+
758
+ - [Getting Started Guide](./docs/getting-started.md) - Installation, setup, and your first workflow
759
+ - [Architecture Overview](./docs/architecture.md) - Core concepts, design principles, and system overview
760
+ - [Examples Index](./docs/examples.md) - Browse all code examples and use cases
761
+
762
+ ### Core Features
763
+
764
+ - [Workflows](./docs/workflows.md) - Sequential, parallel, collaborative, and conditional patterns
765
+ - [Graph Execution](./docs/graph-execution.md) - DAG/Cyclic workflows with complex logic and loops
766
+ - [Pipeline Patterns](./docs/pipeline-patterns.md) - Chain, scatter-gather, router, splitter, saga patterns
767
+ - [Aggregation Strategies](./docs/aggregation-strategies.md) - Consensus, voting, weighted, best-of, custom reducers
768
+
769
+ ### Data & State
770
+
771
+ - [Tool Calling](./docs/tool-calling.md) - External tools and APIs integration with JSON Schema validation
772
+ - [Memory System](./docs/memory-system.md) - Multi-level context (short-term, long-term, entity memory)
773
+ - [Context System](./docs/context-system.md) - Type-safe state sharing with tokens and providers
774
+ - [Structured Output](./docs/structured-output.md) - JSON Schema validation with automatic retry
775
+
776
+ ### Observability & Performance
777
+
778
+ - [Event System](./docs/event-system.md) - Lifecycle events, progress tracking, and debugging hooks
779
+ - [Metrics & Observability](./docs/metrics-observability.md) - Token counting, cost estimation, performance profiling
780
+ - [Middleware System](./docs/middleware-system.md) - Logging, caching, retry, circuit breaker, rate limiting
781
+
782
+ ### Reference
783
+
784
+ - [API Reference](./docs/api-reference.md) - Complete API documentation with all interfaces and methods
785
+ - [Advanced Features](./docs/advanced.md) - Error handling, timeout, cancellation, performance tuning
786
+ - [Migration Guide](./docs/migration.md) - Upgrading from legacy API to modern fluent builder API
787
+
788
+ ## ๐Ÿ’ก Examples
789
+
790
+ Check out the [examples](./examples) directory for complete working examples:
791
+
792
+ - **Basic Examples**: Simple societies, multi-model usage, observers
793
+ - **Roles & Agents**: Custom roles, agent capabilities, communication
794
+ - **Workflows**: Sequential, parallel, collaborative, conditional
795
+ - **Domain Examples**: Software teams, research teams, creative teams, business teams
796
+ - **Integrations**: OpenAI, Anthropic, custom APIs
797
+ - **Advanced**: Error handling, timeouts, lifecycle hooks, result transformers
798
+
799
+ ## ๐Ÿงช Testing
800
+
801
+ Run the test suite:
802
+
803
+ ```bash
804
+ npm test
805
+ ```
806
+
807
+ Run tests in watch mode:
808
+
809
+ ```bash
810
+ npm run test:watch
811
+ ```
812
+
813
+ Generate coverage report:
814
+
815
+ ```bash
816
+ npm run test:coverage
817
+ ```
818
+
819
+ ## ๐Ÿ—๏ธ Development
820
+
821
+ Build the project:
822
+
823
+ ```bash
824
+ npm run build
825
+ ```
826
+
827
+ Watch mode for development:
828
+
829
+ ```bash
830
+ npm run watch
831
+ ```
832
+
833
+ Lint code:
834
+
835
+ ```bash
836
+ npm run lint
837
+ ```
838
+
839
+ Format code:
840
+
841
+ ```bash
842
+ npm run format
843
+ ```
844
+
845
+ ## ๐Ÿค Contributing
846
+
847
+ Contributions are welcome! Please see [CONTRIBUTING.md](./CONTRIBUTING.md) for guidelines.
848
+
849
+ 1. Fork the repository
850
+ 2. Create your feature branch (`git checkout -b feature/amazing-feature`)
851
+ 3. Commit your changes (`git commit -m 'Add amazing feature'`)
852
+ 4. Push to the branch (`git push origin feature/amazing-feature`)
853
+ 5. Open a Pull Request
854
+
855
+ ## ๐Ÿ“„ License
856
+
857
+ This project is licensed under the MIT License - see the [LICENSE](./LICENSE) file for details.
858
+
859
+ ## ๐Ÿ”— Links
860
+
861
+ - **Documentation**: [docs/](./docs/) - Full documentation
862
+ - **npm Package**: [societyai](https://www.npmjs.com/package/societyai)
863
+ - **Examples**: See [Examples Index](./docs/examples.md) (coming soon)
864
+ - **Changelog**: [CHANGELOG.md](./CHANGELOG.md)
865
+ - **Issues**: [GitHub Issues](https://github.com/benoitpetit/societyai-package/issues)
866
+
867
+ ## ๐Ÿ™ Acknowledgments
868
+
869
+ Built with TypeScript and designed for flexibility, extensibility, and developer experience.
870
+
871
+ ## ๐Ÿ“ž Support
872
+
873
+ - ๐Ÿ“ง Email: [Create an issue](https://github.com/benoitpetit/societyai-package/issues)
874
+ - ๐Ÿ’ฌ Discussions: [GitHub Discussions](https://github.com/benoitpetit/societyai-package/discussions)
875
+ - ๐Ÿ“ Documentation: [Full Documentation](./docs/)
876
+
877
+ ---
878
+
879
+ **Made with โค๏ธ by the SocietyAI community**