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,234 @@
1
+ # SocietyAI Examples
2
+
3
+ This directory contains comprehensive examples demonstrating all features of SocietyAI.
4
+
5
+ ## Available Examples
6
+
7
+ ### 1. Graph-Based Workflow (`graph-workflow.ts`)
8
+
9
+ Demonstrates the new graph-based execution engine with:
10
+
11
+ - Conditional branching
12
+ - Loop support
13
+ - Parallel execution
14
+ - Dynamic routing
15
+
16
+ **Run:**
17
+
18
+ ```bash
19
+ ts-node examples/graph-workflow.ts
20
+ ```
21
+
22
+ ### 2. Tool Calling System (`tool-calling.ts`)
23
+
24
+ Shows how agents can use tools to:
25
+
26
+ - Perform calculations
27
+ - Manipulate strings
28
+ - Store and retrieve data
29
+ - Call custom functions
30
+
31
+ **Run:**
32
+
33
+ ```bash
34
+ ts-node examples/tool-calling.ts
35
+ ```
36
+
37
+ ### 3. Memory System (`memory-system.ts`)
38
+
39
+ Demonstrates multi-level memory:
40
+
41
+ - Short-term conversation history
42
+ - Long-term fact storage
43
+ - Entity tracking
44
+ - Importance-based retrieval
45
+
46
+ **Run:**
47
+
48
+ ```bash
49
+ ts-node examples/memory-system.ts
50
+ ```
51
+
52
+ ### 4. Structured Output Validation (`structured-output.ts`)
53
+
54
+ Shows automatic validation with retry:
55
+
56
+ - JSON Schema validation
57
+ - Error feedback to agents
58
+ - Automatic retry logic
59
+ - Complex nested schemas
60
+
61
+ **Run:**
62
+
63
+ ```bash
64
+ ts-node examples/structured-output.ts
65
+ ```
66
+
67
+ ### 5. Metrics and Observability (`metrics-tracking.ts`)
68
+
69
+ Comprehensive tracking of:
70
+
71
+ - Token usage
72
+ - Execution time
73
+ - Cost estimation
74
+ - OpenTelemetry export
75
+ - Performance profiling
76
+
77
+ **Run:**
78
+
79
+ ```bash
80
+ ts-node examples/metrics-tracking.ts
81
+ ```
82
+
83
+ ### 6. Complete Integration (`complete-integration.ts`)
84
+
85
+ End-to-end example using all features together:
86
+
87
+ - Graph-based workflow
88
+ - Tool calling
89
+ - Memory system
90
+ - Output validation
91
+ - Metrics tracking
92
+
93
+ **Run:**
94
+
95
+ ```bash
96
+ ts-node examples/complete-integration.ts
97
+ ```
98
+
99
+ ## Running All Examples
100
+
101
+ ```bash
102
+ npm run examples
103
+ ```
104
+
105
+ Or run them individually:
106
+
107
+ ```bash
108
+ # Graph workflow
109
+ npm run example:graph
110
+
111
+ # Tool calling
112
+ npm run example:tools
113
+
114
+ # Memory system
115
+ npm run example:memory
116
+
117
+ # Structured output
118
+ npm run example:validation
119
+
120
+ # Metrics tracking
121
+ npm run example:metrics
122
+
123
+ # Complete integration
124
+ npm run example:complete
125
+ ```
126
+
127
+ ## Key Concepts Demonstrated
128
+
129
+ ### Graph-Based Execution
130
+
131
+ - **DAG Support**: Directed Acyclic Graphs for complex workflows
132
+ - **Conditional Edges**: Dynamic routing based on runtime conditions
133
+ - **Loop Support**: Iterative processing with termination conditions
134
+ - **Parallel Execution**: Run multiple agents simultaneously
135
+
136
+ ### Tool Calling
137
+
138
+ - **Function Definitions**: JSON Schema-based tool definitions
139
+ - **Parameter Validation**: Automatic validation of tool inputs
140
+ - **Result Handling**: Structured tool result processing
141
+ - **Error Recovery**: Retry logic for failed tool calls
142
+
143
+ ### Memory System
144
+
145
+ - **Short-Term Memory**: Recent conversation with auto-summarization
146
+ - **Long-Term Memory**: Persistent facts with semantic search
147
+ - **Entity Memory**: Track specific entities and their facts
148
+ - **Importance Scoring**: Priority-based memory retrieval
149
+
150
+ ### Structured Output
151
+
152
+ - **Schema Validation**: JSON Schema-based validation
153
+ - **Automatic Retry**: Retry with error feedback
154
+ - **Type Safety**: Fully typed validated outputs
155
+ - **Complex Schemas**: Support for nested objects and arrays
156
+
157
+ ### Observability
158
+
159
+ - **Token Tracking**: Per-agent token usage monitoring
160
+ - **Cost Estimation**: Automatic cost calculation
161
+ - **Performance Profiling**: Detailed timing metrics
162
+ - **OpenTelemetry**: Industry-standard trace export
163
+
164
+ ## Advanced Patterns
165
+
166
+ ### Combining Features
167
+
168
+ ```typescript
169
+ // Create a graph with tools, memory, and validation
170
+ const graph = GraphBuilder.create()
171
+ .addNode('agent-with-tools', NodeType.AGENT, {
172
+ agentId: 'tool-user',
173
+ memory: memorySystem,
174
+ validator: outputValidator,
175
+ })
176
+ .build();
177
+
178
+ // Execute with full metrics
179
+ tracker.start('workflow');
180
+ const result = await graph.execute(input, agents);
181
+ tracker.end('workflow', { tokens: tokenMetrics });
182
+ ```
183
+
184
+ ### Real-World Use Cases
185
+
186
+ 1. **Code Review Pipeline**: Analyze → Fix → Validate loop with tools
187
+ 2. **Data Processing**: Parallel processing with aggregation
188
+ 3. **Research Assistant**: Memory-enhanced information gathering
189
+ 4. **API Integration**: Tool calling for external services
190
+ 5. **Quality Assurance**: Structured output validation for consistency
191
+
192
+ ## Best Practices
193
+
194
+ 1. **Memory Management**: Balance short-term and long-term storage
195
+ 2. **Tool Design**: Keep tools focused and well-documented
196
+ 3. **Schema Design**: Start simple, add complexity as needed
197
+ 4. **Metrics Collection**: Track what matters for your use case
198
+ 5. **Graph Design**: Minimize cycles, use conditions wisely
199
+
200
+ ## Troubleshooting
201
+
202
+ ### Common Issues
203
+
204
+ **Graph validation fails:**
205
+
206
+ - Ensure START and END nodes exist
207
+ - Check all edges reference valid nodes
208
+ - Verify conditional logic is correct
209
+
210
+ **Tool execution fails:**
211
+
212
+ - Validate parameter schemas match tool definitions
213
+ - Check required parameters are provided
214
+ - Ensure tool executors handle errors
215
+
216
+ **Memory retrieval is slow:**
217
+
218
+ - Limit result count with `limit` parameter
219
+ - Use importance scoring for prioritization
220
+ - Consider implementing vector provider for semantic search
221
+
222
+ **Validation keeps retrying:**
223
+
224
+ - Check schema matches expected output format
225
+ - Verify agent understands schema requirements
226
+ - Add schema description to agent prompt
227
+
228
+ ## Contributing
229
+
230
+ Found a bug or want to add a new example? Please submit a pull request or open an issue on GitHub.
231
+
232
+ ## License
233
+
234
+ MIT License - see LICENSE file for details
@@ -0,0 +1,115 @@
1
+ import {
2
+ GraphBuilder,
3
+ NodeType,
4
+ SocietyAsModel,
5
+ PipelinePatterns,
6
+ AgentBuilder,
7
+ RoleBuilder,
8
+ AIModel
9
+ } from '../src';
10
+
11
+ // Simple Mock Model for demonstration
12
+ class MockModel implements AIModel {
13
+ constructor(private nameStr: string) {}
14
+
15
+ name(): string { return this.nameStr; }
16
+
17
+ async process(prompt: unknown): Promise<string> {
18
+ return `[Response from ${this.nameStr} to: "${String(prompt).substring(0, 20)}..."]`;
19
+ }
20
+
21
+ supportsPromptType(): boolean { return true; }
22
+ }
23
+
24
+ async function demonstrateRecursiveSociety(): Promise<void> {
25
+ console.log('=== Recursive Society Demo ===');
26
+
27
+ // 1. Create a Sub-Society (e.g., a "Translation Team")
28
+ const translator = AgentBuilder.create()
29
+ .withId('translator')
30
+ .withName('Translator')
31
+ .withRole(RoleBuilder.create().withId('translator').withSystemPrompt('Translate to French').build())
32
+ .withModel(new MockModel('TranslatorBot'))
33
+ .build();
34
+
35
+ const editor = AgentBuilder.create()
36
+ .withId('editor')
37
+ .withName('Editor')
38
+ .withRole(RoleBuilder.create().withId('editor').withSystemPrompt('Fix grammar').build())
39
+ .withModel(new MockModel('EditorBot'))
40
+ .build();
41
+
42
+ const teamGraph = GraphBuilder.create()
43
+ .addNode('start', NodeType.START)
44
+ .addNode('translate', NodeType.AGENT, { agentId: 'translator' })
45
+ .addNode('edit', NodeType.AGENT, { agentId: 'editor' })
46
+ .addNode('end', NodeType.END)
47
+ .addEdge('start', 'translate')
48
+ .addEdge('translate', 'edit')
49
+ .addEdge('edit', 'end')
50
+ .build();
51
+
52
+ // Wrap the society as an AI Model
53
+ const translationTeamModel = new SocietyAsModel(
54
+ teamGraph,
55
+ [translator, editor],
56
+ { name: 'TranslationTeam' }
57
+ );
58
+
59
+ // 2. Create the Main Society that uses the sub-society
60
+ const projectManager = AgentBuilder.create()
61
+ .withId('pm')
62
+ .withName('ProjectManager')
63
+ .withRole(RoleBuilder.create().withId('pm').withSystemPrompt('Manage project').build())
64
+ .withModel(new MockModel('ManagerBot'))
65
+ .build();
66
+
67
+ const translationAgent = AgentBuilder.create()
68
+ .withId('translation_dept')
69
+ .withName('Translation Department')
70
+ .withRole(RoleBuilder.create().withId('dept').withSystemPrompt('Handle translations').build())
71
+ .withModel(translationTeamModel) // Using the sub-society as the model
72
+ .build();
73
+
74
+ const companyGraph = GraphBuilder.create()
75
+ .addNode('start', NodeType.START)
76
+ .addNode('plan', NodeType.AGENT, { agentId: 'pm' })
77
+ .addNode('execute', NodeType.AGENT, { agentId: 'translation_dept' })
78
+ .addNode('end', NodeType.END)
79
+ .addEdge('start', 'plan')
80
+ .addEdge('plan', 'execute')
81
+ .addEdge('execute', 'end')
82
+ .build();
83
+
84
+ console.log('Main Society Structure (Mermaid):');
85
+ console.log(companyGraph.toMermaid());
86
+
87
+ // Execute
88
+ const result = await companyGraph.execute(
89
+ 'Please translate the documentation',
90
+ [projectManager, translationAgent]
91
+ );
92
+
93
+ console.log('\nFinal Output:', result.output);
94
+ }
95
+
96
+ async function demonstratePatterns(): Promise<void> {
97
+ console.log('\n=== Patterns Demo ===');
98
+
99
+ // Create a Self-Correction Graph
100
+ const correctionGraph = PipelinePatterns.selfCorrection(
101
+ 'generator_agent',
102
+ 'validator_agent',
103
+ 3
104
+ );
105
+
106
+ console.log('Self-Correction Pattern Structure:');
107
+ console.log(correctionGraph.visualize());
108
+ }
109
+
110
+ async function main(): Promise<void> {
111
+ await demonstrateRecursiveSociety();
112
+ await demonstratePatterns();
113
+ }
114
+
115
+ main().catch(console.error);
@@ -0,0 +1,327 @@
1
+ /**
2
+ * Example: Complete Integration
3
+ *
4
+ * This example demonstrates all new features working together:
5
+ * - Graph-based execution
6
+ * - Tool calling
7
+ * - Memory system
8
+ * - Structured output validation
9
+ * - Metrics tracking
10
+ */
11
+
12
+ import {
13
+ GraphBuilder,
14
+ NodeType,
15
+ ToolRegistry,
16
+ ToolExecutor,
17
+ ToolBuilder,
18
+ MemoryBuilder,
19
+ MemorySystem,
20
+ StructuredOutputValidator,
21
+ createSchema,
22
+ MetricsBuilder,
23
+ CommonCostConfigs,
24
+ AgentBuilder,
25
+ RoleBuilder,
26
+ StandardModelBase,
27
+ } from '../src';
28
+
29
+ // Advanced AI Model with all features
30
+ class AdvancedModel extends StandardModelBase {
31
+ constructor(
32
+ name: string,
33
+ private memory: MemorySystem,
34
+ private toolExecutor: ToolExecutor,
35
+ private validator?: StructuredOutputValidator
36
+ ) {
37
+ super({ name }, async (prompt: unknown) => {
38
+ const promptStr = typeof prompt === 'string' ? prompt : JSON.stringify(prompt);
39
+
40
+ // Retrieve relevant context from memory
41
+ const context = await this.memory.retrieve(promptStr, { limit: 3 });
42
+
43
+ // Generate response with context
44
+ let response = `Based on context:\n${context}\n\n`;
45
+
46
+ if (promptStr.includes('calculate')) {
47
+ response += '{"tool": "calculator", "parameters": {"expression": "100 * 5"}}';
48
+ } else if (promptStr.includes('user data')) {
49
+ response = `{
50
+ "name": "Alice Johnson",
51
+ "age": 28,
52
+ "email": "alice@example.com",
53
+ "role": "Software Engineer",
54
+ "skills": ["TypeScript", "React", "Node.js"]
55
+ }`;
56
+ } else {
57
+ response += 'Analysis complete. Ready for next step.';
58
+ }
59
+
60
+ // Store in memory
61
+ await this.memory.add(response, {
62
+ type: 'conversation',
63
+ importance: 0.7,
64
+ });
65
+
66
+ return response;
67
+ });
68
+ }
69
+ }
70
+
71
+ async function runCompleteExample(): Promise<void> {
72
+ console.log('=== Complete Integration Example ===\n');
73
+ console.log('This example combines all new features:\n');
74
+ console.log('āœ“ Graph-based workflow execution');
75
+ console.log('āœ“ Tool calling capabilities');
76
+ console.log('āœ“ Multi-level memory system');
77
+ console.log('āœ“ Structured output validation');
78
+ console.log('āœ“ Comprehensive metrics tracking\n');
79
+
80
+ // 1. Setup Metrics Tracker
81
+ console.log('--- Setting up Metrics Tracker ---');
82
+ const tracker = MetricsBuilder.create()
83
+ .withTokenTracking()
84
+ .withCostTracking(CommonCostConfigs['gpt-4'])
85
+ .build();
86
+
87
+ tracker.start('complete-workflow', { scenario: 'user-onboarding' });
88
+
89
+ // 2. Setup Memory System
90
+ console.log('--- Initializing Memory System ---');
91
+ const memory = MemoryBuilder.create()
92
+ .withShortTermMemory({ maxMessages: 20 })
93
+ .withLongTermMemory({ maxEntries: 100 })
94
+ .build();
95
+
96
+ // Add some initial knowledge
97
+ await memory.add('System supports user onboarding workflow', {
98
+ type: 'fact',
99
+ importance: 1.0,
100
+ });
101
+
102
+ await memory.add('Users must provide name, email, and role', {
103
+ type: 'fact',
104
+ importance: 0.9,
105
+ });
106
+
107
+ // Add entity
108
+ memory.getEntities().upsert('UserOnboardingService', 'service', [
109
+ 'Validates user data',
110
+ 'Stores user profiles',
111
+ 'Sends welcome emails',
112
+ ]);
113
+
114
+ // 3. Setup Tool Registry
115
+ console.log('--- Registering Tools ---');
116
+ const toolRegistry = new ToolRegistry();
117
+
118
+ // Calculator tool
119
+ const calculatorTool = ToolBuilder.create()
120
+ .withName('calculator')
121
+ .withDescription('Perform calculations')
122
+ .withParameters({
123
+ type: 'object',
124
+ properties: {
125
+ expression: { type: 'string' },
126
+ },
127
+ required: ['expression'],
128
+ })
129
+ .withExecutor(async (params) => {
130
+ const result = eval(params.expression as string);
131
+ return { result };
132
+ })
133
+ .build();
134
+
135
+ // Email sender tool
136
+ const emailTool = ToolBuilder.create()
137
+ .withName('send_email')
138
+ .withDescription('Send email to user')
139
+ .withParameters({
140
+ type: 'object',
141
+ properties: {
142
+ to: { type: 'string' },
143
+ subject: { type: 'string' },
144
+ body: { type: 'string' },
145
+ },
146
+ required: ['to', 'subject', 'body'],
147
+ })
148
+ .withExecutor(async (params) => {
149
+ console.log(` šŸ“§ Email sent to ${params.to}`);
150
+ return { success: true, messageId: 'msg_' + Date.now() };
151
+ })
152
+ .build();
153
+
154
+ toolRegistry.register(calculatorTool);
155
+ toolRegistry.register(emailTool);
156
+
157
+ const toolExecutor = new ToolExecutor(toolRegistry);
158
+
159
+ // 4. Setup Structured Output Validator
160
+ console.log('--- Configuring Validation Schema ---');
161
+ const userSchema = createSchema({
162
+ name: { type: 'string', required: true },
163
+ age: { type: 'number', required: true },
164
+ email: { type: 'string', required: true },
165
+ role: { type: 'string', required: true },
166
+ skills: { type: 'array', required: false },
167
+ });
168
+
169
+ const validator = new StructuredOutputValidator(userSchema);
170
+
171
+ // 5. Create Agents with Advanced Models
172
+ console.log('--- Creating Intelligent Agents ---');
173
+
174
+ const dataCollectorRole = RoleBuilder.create()
175
+ .withId('data-collector')
176
+ .withName('Data Collector')
177
+ .withSystemPrompt('You collect and validate user data.')
178
+ .build();
179
+
180
+ const validatorRole = RoleBuilder.create()
181
+ .withId('validator')
182
+ .withName('Data Validator')
183
+ .withSystemPrompt('You validate user data against schema.')
184
+ .build();
185
+
186
+ const notifierRole = RoleBuilder.create()
187
+ .withId('notifier')
188
+ .withName('Notification Service')
189
+ .withSystemPrompt('You send notifications to users.')
190
+ .build();
191
+
192
+ const agents = [
193
+ AgentBuilder.create()
194
+ .withId('collector-1')
195
+ .withRole(dataCollectorRole)
196
+ .withModel(new AdvancedModel('collector-model', memory, toolExecutor, validator))
197
+ .build(),
198
+
199
+ AgentBuilder.create()
200
+ .withId('validator-1')
201
+ .withRole(validatorRole)
202
+ .withModel(new AdvancedModel('validator-model', memory, toolExecutor, validator))
203
+ .build(),
204
+
205
+ AgentBuilder.create()
206
+ .withId('notifier-1')
207
+ .withRole(notifierRole)
208
+ .withModel(new AdvancedModel('notifier-model', memory, toolExecutor))
209
+ .build(),
210
+ ];
211
+
212
+ // 6. Build Execution Graph
213
+ console.log('--- Building Execution Graph ---');
214
+ const graph = GraphBuilder.create()
215
+ .addNode('start', NodeType.START)
216
+
217
+ // Collect user data
218
+ .addNode('collect', NodeType.AGENT, { agentId: 'collector-1' })
219
+
220
+ // Validate the data
221
+ .addNode('validate', NodeType.AGENT, { agentId: 'validator-1' })
222
+
223
+ // Check if validation passed
224
+ .addNode('is-valid', NodeType.CONDITION, {
225
+ condition: (result) => result.includes('"email"') && result.includes('@'),
226
+ })
227
+
228
+ // Calculate onboarding bonus (example tool usage)
229
+ .addNode('calculate-bonus', NodeType.TRANSFORM, {
230
+ transformer: (result) => {
231
+ return result + '\nOnboarding bonus: $500';
232
+ },
233
+ })
234
+
235
+ // Send welcome email
236
+ .addNode('notify', NodeType.AGENT, { agentId: 'notifier-1' })
237
+
238
+ // Final formatting
239
+ .addNode('format', NodeType.TRANSFORM, {
240
+ transformer: (result) => `āœ… User Onboarded Successfully\n\n${result}`,
241
+ })
242
+
243
+ .addNode('end', NodeType.END)
244
+
245
+ // Connect nodes
246
+ .addEdge('start', 'collect')
247
+ .addEdge('collect', 'validate')
248
+ .addEdge('validate', 'is-valid')
249
+
250
+ .addConditionalEdge({
251
+ from: 'is-valid',
252
+ condition: (result) => result.includes('"email"') && result.includes('@'),
253
+ truePath: 'calculate-bonus',
254
+ falsePath: 'collect', // Retry data collection
255
+ })
256
+
257
+ .addEdge('calculate-bonus', 'notify')
258
+ .addEdge('notify', 'format')
259
+ .addEdge('format', 'end')
260
+
261
+ .build();
262
+
263
+ // 7. Execute the Complete Workflow
264
+ console.log('\n--- Executing Complete Workflow ---\n');
265
+
266
+ const result = await graph.execute(
267
+ 'Onboard new user: Please collect user data, validate it, and send welcome notification.',
268
+ agents
269
+ );
270
+
271
+ console.log('\n--- Workflow Results ---');
272
+ console.log('Output:', result.output);
273
+ console.log('\nExecution path:', result.executionPath.join(' → '));
274
+ console.log('Duration:', result.duration, 'ms');
275
+ console.log('Success:', result.success);
276
+
277
+ // 8. Collect and Display Metrics
278
+ console.log('\n--- Performance Metrics ---');
279
+
280
+ const metrics = tracker.end('complete-workflow', {
281
+ tokens: {
282
+ inputTokens: 1200,
283
+ outputTokens: 800,
284
+ totalTokens: 2000,
285
+ model: 'gpt-4',
286
+ },
287
+ custom: {
288
+ nodesExecuted: result.nodeResults.size,
289
+ toolCalls: 2,
290
+ },
291
+ });
292
+
293
+ console.log('Total duration:', metrics.execution.duration, 'ms');
294
+ console.log('Tokens used:', metrics.tokens?.totalTokens);
295
+ console.log('Estimated cost:', `$${metrics.cost?.totalCost.toFixed(4)}`);
296
+ console.log('Nodes executed:', metrics.custom?.nodesExecuted);
297
+
298
+ // 9. Display Memory State
299
+ console.log('\n--- Memory State ---');
300
+ const memoryStats = memory.getStats();
301
+ console.log('Short-term messages:', memoryStats.shortTerm.messages);
302
+ console.log('Long-term facts:', memoryStats.longTerm.total);
303
+ console.log('Entities tracked:', memoryStats.entities.total);
304
+
305
+ // 10. Display Recent Conversations
306
+ console.log('\n--- Recent Memory ---');
307
+ const recentMemories = memory.getShortTerm().getRecent(3);
308
+ recentMemories.forEach((mem, idx) => {
309
+ console.log(`${idx + 1}. ${mem.content.substring(0, 100)}...`);
310
+ });
311
+
312
+ // 11. Export Telemetry
313
+ console.log('\n--- Exporting Telemetry ---');
314
+ const otelTraces = tracker.exportOTel();
315
+ console.log('Generated', otelTraces.length, 'OpenTelemetry traces');
316
+ console.log('Ready for export to observability platform');
317
+
318
+ console.log('\nāœ… Complete workflow executed successfully!');
319
+ console.log('All systems integrated and working together.');
320
+ }
321
+
322
+ // Run the example
323
+ if (require.main === module) {
324
+ runCompleteExample().catch(console.error);
325
+ }
326
+
327
+ export { runCompleteExample };