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,231 @@
1
+ /**
2
+ * Example: Structured Output with Validation
3
+ *
4
+ * This example demonstrates automatic JSON validation with retry logic
5
+ * to ensure AI outputs match expected schemas.
6
+ */
7
+
8
+ import {
9
+ StructuredOutputBuilder,
10
+ StructuredOutputValidator,
11
+ createSchema,
12
+ validateJSON,
13
+ JSONSchema,
14
+ StandardModelBase,
15
+ } from '../src';
16
+
17
+ // Mock AI Model that generates JSON
18
+ class JSONGeneratingModel extends StandardModelBase {
19
+ private attemptCount = 0;
20
+
21
+ constructor() {
22
+ super({ name: 'json-generator' }, async (_prompt: unknown) => {
23
+ this.attemptCount++;
24
+
25
+ // First attempt: Invalid JSON
26
+ if (this.attemptCount === 1) {
27
+ return `Here's the user data:
28
+ {
29
+ "name": "John Doe",
30
+ "age": "thirty",
31
+ "email": "invalid-email"
32
+ }`;
33
+ }
34
+
35
+ // Second attempt: Valid JSON
36
+ return `{
37
+ "name": "John Doe",
38
+ "age": 30,
39
+ "email": "john@example.com",
40
+ "isActive": true
41
+ }`;
42
+ });
43
+ }
44
+
45
+ resetAttempts(): void {
46
+ this.attemptCount = 0;
47
+ }
48
+ }
49
+
50
+ async function runValidationExample(): Promise<void> {
51
+ console.log('=== Structured Output Validation Example ===\n');
52
+
53
+ // Define JSON schema
54
+ const userSchema: JSONSchema = {
55
+ type: 'object',
56
+ properties: {
57
+ name: { type: 'string', minLength: 1 },
58
+ age: { type: 'number', minimum: 0, maximum: 150 },
59
+ email: { type: 'string', pattern: '^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,}$' },
60
+ isActive: { type: 'boolean' },
61
+ },
62
+ required: ['name', 'age', 'email'],
63
+ };
64
+
65
+ console.log('Expected Schema:');
66
+ console.log(JSON.stringify(userSchema, null, 2));
67
+ console.log();
68
+
69
+ // Create validator
70
+ const validator = StructuredOutputBuilder.create()
71
+ .withSchema(userSchema)
72
+ .withMaxRetries(3)
73
+ .build();
74
+
75
+ // Test 1: Invalid output
76
+ console.log('--- Test 1: Validating Invalid Output ---');
77
+
78
+ const invalidOutput = `{
79
+ "name": "John",
80
+ "age": "thirty",
81
+ "email": "not-an-email"
82
+ }`;
83
+
84
+ const result1 = validator.validate(invalidOutput);
85
+ console.log('Valid:', result1.valid);
86
+
87
+ if (!result1.valid && result1.errors) {
88
+ console.log('Errors found:');
89
+ result1.errors.forEach(err => {
90
+ console.log(` - ${err.path}: ${err.message}`);
91
+ if (err.expected) console.log(` Expected: ${err.expected}`);
92
+ if (err.actual) console.log(` Actual: ${JSON.stringify(err.actual)}`);
93
+ });
94
+ }
95
+
96
+ // Test 2: Valid output
97
+ console.log('\n--- Test 2: Validating Valid Output ---');
98
+
99
+ const validOutput = `{
100
+ "name": "John Doe",
101
+ "age": 30,
102
+ "email": "john@example.com",
103
+ "isActive": true
104
+ }`;
105
+
106
+ const result2 = validator.validate(validOutput);
107
+ console.log('Valid:', result2.valid);
108
+
109
+ if (result2.valid && result2.data) {
110
+ console.log('Parsed data:', result2.data);
111
+ }
112
+
113
+ // Test 3: Automatic retry with AI model
114
+ console.log('\n--- Test 3: Automatic Retry with Error Feedback ---');
115
+
116
+ const model = new JSONGeneratingModel();
117
+
118
+ const agentOutput = await model.process('Generate user data');
119
+ console.log('Initial AI output:');
120
+ console.log(agentOutput);
121
+ console.log();
122
+
123
+ const result3 = await validator.validateAndRetry(
124
+ agentOutput,
125
+ async (errorFeedback) => {
126
+ console.log('Retry triggered with feedback:');
127
+ console.log(errorFeedback);
128
+ console.log();
129
+
130
+ // Agent retries with error feedback
131
+ return await model.process(`Previous attempt had errors:\n${errorFeedback}\n\nPlease correct and generate valid JSON.`);
132
+ }
133
+ );
134
+
135
+ console.log('Final validation result:');
136
+ console.log('Valid:', result3.valid);
137
+
138
+ if (result3.valid && result3.data) {
139
+ console.log('Successfully parsed data:', result3.data);
140
+ }
141
+
142
+ // Test 4: Quick validation helper
143
+ console.log('\n--- Test 4: Quick Validation Helper ---');
144
+
145
+ const quickResult = validateJSON(validOutput, userSchema);
146
+ console.log('Quick validate:', quickResult.valid);
147
+
148
+ // Test 5: Create schema from object
149
+ console.log('\n--- Test 5: Create Schema from Properties ---');
150
+
151
+ const dynamicSchema = createSchema({
152
+ title: { type: 'string', required: true, description: 'Article title' },
153
+ content: { type: 'string', required: true, description: 'Article content' },
154
+ views: { type: 'number', required: false, description: 'View count' },
155
+ published: { type: 'boolean', required: false, description: 'Publication status' },
156
+ });
157
+
158
+ console.log('Generated schema:');
159
+ console.log(JSON.stringify(dynamicSchema, null, 2));
160
+
161
+ const articleValidator = new StructuredOutputValidator(dynamicSchema);
162
+ const articleOutput = `{
163
+ "title": "Understanding TypeScript",
164
+ "content": "TypeScript is a powerful language...",
165
+ "views": 1250,
166
+ "published": true
167
+ }`;
168
+
169
+ const articleResult = articleValidator.validate(articleOutput);
170
+ console.log('\nValidation result:', articleResult.valid);
171
+
172
+ if (articleResult.valid) {
173
+ console.log('Article data:', articleResult.data);
174
+ }
175
+
176
+ // Test 6: Complex nested schema
177
+ console.log('\n--- Test 6: Complex Nested Schema ---');
178
+
179
+ const complexSchema: JSONSchema = {
180
+ type: 'object',
181
+ properties: {
182
+ user: {
183
+ type: 'object',
184
+ properties: {
185
+ id: { type: 'number' },
186
+ profile: {
187
+ type: 'object',
188
+ properties: {
189
+ bio: { type: 'string' },
190
+ location: { type: 'string' },
191
+ },
192
+ required: ['bio'],
193
+ },
194
+ },
195
+ required: ['id', 'profile'],
196
+ },
197
+ tags: {
198
+ type: 'array',
199
+ items: { type: 'string' },
200
+ minItems: 1,
201
+ },
202
+ },
203
+ required: ['user', 'tags'],
204
+ };
205
+
206
+ const complexOutput = `{
207
+ "user": {
208
+ "id": 123,
209
+ "profile": {
210
+ "bio": "Software developer",
211
+ "location": "San Francisco"
212
+ }
213
+ },
214
+ "tags": ["typescript", "javascript", "react"]
215
+ }`;
216
+
217
+ const complexValidator = new StructuredOutputValidator(complexSchema);
218
+ const complexResult = complexValidator.validate(complexOutput);
219
+
220
+ console.log('Complex validation:', complexResult.valid);
221
+ if (complexResult.valid) {
222
+ console.log('Complex data:', JSON.stringify(complexResult.data, null, 2));
223
+ }
224
+ }
225
+
226
+ // Run the example
227
+ if (require.main === module) {
228
+ runValidationExample().catch(console.error);
229
+ }
230
+
231
+ export { runValidationExample };
@@ -0,0 +1,163 @@
1
+ /**
2
+ * Example: Tool Calling System
3
+ *
4
+ * This example demonstrates how agents can use tools to perform
5
+ * actions like calculations, web searches, and data storage.
6
+ */
7
+
8
+ import {
9
+ ToolBuilder,
10
+ ToolRegistry,
11
+ ToolExecutor,
12
+ BuiltInTools,
13
+ AgentBuilder,
14
+ RoleBuilder,
15
+ StandardModelBase,
16
+ } from '../src';
17
+
18
+ // Mock AI Model that calls tools
19
+ class ToolCallingModel extends StandardModelBase {
20
+ constructor() {
21
+ super({ name: 'tool-caller' }, async (prompt: unknown) => {
22
+ const promptStr = typeof prompt === 'string' ? prompt : JSON.stringify(prompt);
23
+
24
+ // Simulate tool calling
25
+ if (promptStr.includes('calculate')) {
26
+ return JSON.stringify({
27
+ tool: 'calculator',
28
+ parameters: { expression: '125 * 8 + 42' }
29
+ });
30
+ } else if (promptStr.includes('previous output')) {
31
+ return 'The calculation result is 1042. This is the answer to your question.';
32
+ }
33
+
34
+ return 'I can help you with calculations, string manipulation, and data storage.';
35
+ });
36
+ }
37
+ }
38
+
39
+ async function runToolExample(): Promise<void> {
40
+ console.log('=== Tool Calling Example ===\n');
41
+
42
+ // Create tool registry
43
+ const registry = new ToolRegistry();
44
+
45
+ // Register built-in tools
46
+ registry.register(BuiltInTools.calculator());
47
+ registry.register(BuiltInTools.stringManipulation());
48
+ registry.register(BuiltInTools.storage());
49
+
50
+ // Create a custom tool
51
+ const webSearchTool = ToolBuilder.create()
52
+ .withName('web_search')
53
+ .withDescription('Search the web for information')
54
+ .withParameters({
55
+ type: 'object',
56
+ properties: {
57
+ query: { type: 'string', description: 'Search query' },
58
+ maxResults: { type: 'number', description: 'Max results', default: 5 },
59
+ },
60
+ required: ['query'],
61
+ })
62
+ .withExecutor(async (params) => {
63
+ // Simulate web search
64
+ const query = params.query as string;
65
+ return {
66
+ results: [
67
+ { title: `Result 1 for "${query}"`, url: 'https://example.com/1' },
68
+ { title: `Result 2 for "${query}"`, url: 'https://example.com/2' },
69
+ ],
70
+ };
71
+ })
72
+ .build();
73
+
74
+ registry.register(webSearchTool);
75
+
76
+ console.log('Registered tools:', registry.getAll().map(t => t.name).join(', '));
77
+ console.log();
78
+
79
+ // Create tool executor
80
+ const executor = new ToolExecutor(registry);
81
+
82
+ // Create agent with tools
83
+ const model = new ToolCallingModel();
84
+ const agentRole = RoleBuilder.create()
85
+ .withId('assistant')
86
+ .withName('Tool-Using Assistant')
87
+ .withSystemPrompt('You are an assistant that can use tools to help users.')
88
+ .build();
89
+
90
+ const agent = AgentBuilder.create()
91
+ .withId('assistant-1')
92
+ .withRole(agentRole)
93
+ .withModel(model)
94
+ .build();
95
+
96
+ // Agent executor function
97
+ const agentExecutor = async (input: string): Promise<string> => {
98
+ const prompt = agent.role.promptTemplate?.replace('{input}', input) || input;
99
+ return await agent.model.process(prompt);
100
+ };
101
+
102
+ // Execute agent with tool calling loop
103
+ console.log('Query: What is 125 * 8 + 42?\n');
104
+
105
+ const result = await executor.executeWithTools(
106
+ agentExecutor,
107
+ 'What is 125 * 8 + 42? Please calculate it.',
108
+ undefined,
109
+ 5 // max iterations
110
+ );
111
+
112
+ console.log('Final output:', result.output);
113
+ console.log('\nTool calls made:', result.toolResults.length);
114
+
115
+ for (const toolResult of result.toolResults) {
116
+ console.log(`- ${toolResult.tool}: ${toolResult.success ? '✓' : '✗'}`);
117
+ if (toolResult.result) {
118
+ console.log(` Result:`, toolResult.result);
119
+ }
120
+ }
121
+
122
+ // Test string manipulation tool
123
+ console.log('\n--- String Manipulation ---');
124
+
125
+ const stringResult = await registry.execute({
126
+ name: 'string_manipulation',
127
+ parameters: {
128
+ text: 'Hello World',
129
+ operation: 'reverse',
130
+ },
131
+ });
132
+
133
+ console.log('Reverse "Hello World":', stringResult.result);
134
+
135
+ // Test storage tool
136
+ console.log('\n--- Data Storage ---');
137
+
138
+ await registry.execute({
139
+ name: 'storage',
140
+ parameters: {
141
+ operation: 'set',
142
+ key: 'user_preference',
143
+ value: 'dark_mode',
144
+ },
145
+ });
146
+
147
+ const storedValue = await registry.execute({
148
+ name: 'storage',
149
+ parameters: {
150
+ operation: 'get',
151
+ key: 'user_preference',
152
+ },
153
+ });
154
+
155
+ console.log('Stored value:', storedValue.result);
156
+ }
157
+
158
+ // Run the example
159
+ if (require.main === module) {
160
+ runToolExample().catch(console.error);
161
+ }
162
+
163
+ export { runToolExample };
package/package.json ADDED
@@ -0,0 +1,94 @@
1
+ {
2
+ "name": "societyai",
3
+ "version": "0.0.1",
4
+ "description": "A powerful TypeScript library for creating collaborative multi-agent AI systems. Build sophisticated workflows where AI agents with different roles work together to solve complex problems.",
5
+ "main": "dist/index.js",
6
+ "types": "dist/index.d.ts",
7
+ "module": "dist/index.js",
8
+ "exports": {
9
+ ".": {
10
+ "types": "./dist/index.d.ts",
11
+ "require": "./dist/index.js",
12
+ "import": "./dist/index.js"
13
+ }
14
+ },
15
+ "engines": {
16
+ "node": ">=16.0.0",
17
+ "npm": ">=7.0.0"
18
+ },
19
+ "scripts": {
20
+ "build": "tsc",
21
+ "build:watch": "tsc --watch",
22
+ "watch": "tsc --watch",
23
+ "test": "jest",
24
+ "test:watch": "jest --watch",
25
+ "test:coverage": "jest --coverage",
26
+ "lint": "eslint src --ext .ts",
27
+ "lint:fix": "eslint src --ext .ts --fix",
28
+ "format": "prettier --write \"src/**/*.ts\"",
29
+ "format:check": "prettier --check \"src/**/*.ts\"",
30
+ "typecheck": "tsc --noEmit",
31
+ "validate": "npm run typecheck && npm run lint && npm run test",
32
+ "prepare": "npm run build",
33
+ "prepublishOnly": "npm run validate && npm run build",
34
+ "prepack": "npm run build",
35
+ "check": "node scripts/check-package.js",
36
+ "clean": "rm -rf dist",
37
+ "clean:all": "rm -rf dist node_modules package-lock.json"
38
+ },
39
+ "keywords": [
40
+ "ai",
41
+ "artificial-intelligence",
42
+ "agents",
43
+ "multi-agent",
44
+ "multi-agent-systems",
45
+ "collaboration",
46
+ "llm",
47
+ "large-language-models",
48
+ "prompt",
49
+ "prompt-engineering",
50
+ "society",
51
+ "workflow",
52
+ "orchestration",
53
+ "typescript",
54
+ "openai",
55
+ "anthropic",
56
+ "claude",
57
+ "gpt",
58
+ "chatgpt",
59
+ "model-agnostic",
60
+ "rag",
61
+ "memory",
62
+ "tools",
63
+ "function-calling"
64
+ ],
65
+ "author": "Benoit Petit <contact@societyai.dev> (https://github.com/benoitpetit)",
66
+ "license": "MIT",
67
+ "devDependencies": {
68
+ "@types/jest": "^29.5.11",
69
+ "@types/node": "^20.10.6",
70
+ "@typescript-eslint/eslint-plugin": "^6.17.0",
71
+ "@typescript-eslint/parser": "^6.17.0",
72
+ "eslint": "^8.56.0",
73
+ "jest": "^29.7.0",
74
+ "prettier": "^3.1.1",
75
+ "ts-jest": "^29.1.1",
76
+ "typescript": "^5.3.3"
77
+ },
78
+ "files": [
79
+ "dist",
80
+ "README.md",
81
+ "LICENSE",
82
+ "CHANGELOG.md",
83
+ "docs",
84
+ "examples"
85
+ ],
86
+ "repository": {
87
+ "type": "git",
88
+ "url": "https://github.com/benoitpetit/societyai"
89
+ },
90
+ "bugs": {
91
+ "url": "https://github.com/benoitpetit/societyai/issues"
92
+ },
93
+ "homepage": "https://github.com/benoitpetit/societyai#readme"
94
+ }