@cogitator-ai/swarms 0.3.0 → 0.3.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.
- package/README.md +844 -36
- package/dist/coordinator.d.ts +2 -0
- package/dist/coordinator.d.ts.map +1 -1
- package/dist/coordinator.js +46 -0
- package/dist/coordinator.js.map +1 -1
- package/dist/index.d.ts +4 -3
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +3 -2
- package/dist/index.js.map +1 -1
- package/dist/strategies/index.d.ts +3 -1
- package/dist/strategies/index.d.ts.map +1 -1
- package/dist/strategies/index.js +9 -0
- package/dist/strategies/index.js.map +1 -1
- package/dist/strategies/negotiation/approval.d.ts +28 -0
- package/dist/strategies/negotiation/approval.d.ts.map +1 -0
- package/dist/strategies/negotiation/approval.js +198 -0
- package/dist/strategies/negotiation/approval.js.map +1 -0
- package/dist/strategies/negotiation/convergence.d.ts +22 -0
- package/dist/strategies/negotiation/convergence.d.ts.map +1 -0
- package/dist/strategies/negotiation/convergence.js +240 -0
- package/dist/strategies/negotiation/convergence.js.map +1 -0
- package/dist/strategies/negotiation/index.d.ts +4 -0
- package/dist/strategies/negotiation/index.d.ts.map +1 -0
- package/dist/strategies/negotiation/index.js +4 -0
- package/dist/strategies/negotiation/index.js.map +1 -0
- package/dist/strategies/negotiation/turn-manager.d.ts +31 -0
- package/dist/strategies/negotiation/turn-manager.d.ts.map +1 -0
- package/dist/strategies/negotiation/turn-manager.js +117 -0
- package/dist/strategies/negotiation/turn-manager.js.map +1 -0
- package/dist/strategies/negotiation.d.ts +39 -0
- package/dist/strategies/negotiation.d.ts.map +1 -0
- package/dist/strategies/negotiation.js +607 -0
- package/dist/strategies/negotiation.js.map +1 -0
- package/dist/tools/index.d.ts +2 -1
- package/dist/tools/index.d.ts.map +1 -1
- package/dist/tools/index.js +6 -0
- package/dist/tools/index.js.map +1 -1
- package/dist/tools/negotiation.d.ts +233 -0
- package/dist/tools/negotiation.d.ts.map +1 -0
- package/dist/tools/negotiation.js +445 -0
- package/dist/tools/negotiation.js.map +1 -0
- package/package.json +4 -4
package/README.md
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
# @cogitator-ai/swarms
|
|
2
2
|
|
|
3
|
-
Multi-agent swarm coordination for Cogitator. Orchestrate teams of AI agents with various collaboration strategies.
|
|
3
|
+
Multi-agent swarm coordination for Cogitator. Orchestrate teams of AI agents with various collaboration strategies, automatic model selection, built-in communication primitives, and workflow integration.
|
|
4
4
|
|
|
5
5
|
## Installation
|
|
6
6
|
|
|
@@ -8,82 +8,890 @@ Multi-agent swarm coordination for Cogitator. Orchestrate teams of AI agents wit
|
|
|
8
8
|
pnpm add @cogitator-ai/swarms
|
|
9
9
|
```
|
|
10
10
|
|
|
11
|
-
##
|
|
11
|
+
## Quick Start
|
|
12
12
|
|
|
13
|
-
|
|
13
|
+
```typescript
|
|
14
|
+
import { Cogitator, Agent } from '@cogitator-ai/core';
|
|
15
|
+
import { SwarmBuilder } from '@cogitator-ai/swarms';
|
|
16
|
+
|
|
17
|
+
const cogitator = new Cogitator({ defaultModel: 'gpt-4o' });
|
|
18
|
+
|
|
19
|
+
const swarm = new SwarmBuilder('dev-team')
|
|
20
|
+
.strategy('hierarchical')
|
|
21
|
+
.supervisor(new Agent({ name: 'lead', instructions: 'Coordinate the team' }))
|
|
22
|
+
.workers([
|
|
23
|
+
new Agent({ name: 'coder', instructions: 'Write code' }),
|
|
24
|
+
new Agent({ name: 'tester', instructions: 'Test code' }),
|
|
25
|
+
])
|
|
26
|
+
.build(cogitator);
|
|
27
|
+
|
|
28
|
+
const result = await swarm.run({
|
|
29
|
+
input: 'Build a REST API for user management',
|
|
30
|
+
});
|
|
31
|
+
|
|
32
|
+
console.log(result.output);
|
|
33
|
+
```
|
|
34
|
+
|
|
35
|
+
## Features
|
|
36
|
+
|
|
37
|
+
- **6 Coordination Strategies** - Hierarchical, round-robin, consensus, pipeline, debate, auction
|
|
38
|
+
- **Automatic Model Selection** - SwarmAssessor matches optimal models to agent roles
|
|
39
|
+
- **Agent Communication** - Message bus and shared blackboard
|
|
40
|
+
- **Built-in Tools** - Messaging, delegation, voting, and blackboard tools for agents
|
|
41
|
+
- **Workflow Integration** - Use swarms as nodes in DAG workflows
|
|
42
|
+
- **Resource Tracking** - Monitor tokens, costs, and time budgets
|
|
43
|
+
- **Circuit Breaker** - Prevent cascading failures in swarm execution
|
|
44
|
+
|
|
45
|
+
---
|
|
46
|
+
|
|
47
|
+
## Strategies
|
|
48
|
+
|
|
49
|
+
### Hierarchical
|
|
14
50
|
|
|
15
51
|
Supervisor delegates tasks to workers:
|
|
16
52
|
|
|
17
53
|
```typescript
|
|
18
|
-
import {
|
|
54
|
+
import { SwarmBuilder, Swarm } from '@cogitator-ai/swarms';
|
|
19
55
|
|
|
20
56
|
const swarm = new SwarmBuilder('dev-team')
|
|
21
57
|
.strategy('hierarchical')
|
|
22
|
-
.supervisor(
|
|
23
|
-
|
|
24
|
-
|
|
58
|
+
.supervisor(
|
|
59
|
+
new Agent({
|
|
60
|
+
name: 'tech-lead',
|
|
61
|
+
instructions: 'Break down tasks and delegate to workers',
|
|
62
|
+
})
|
|
63
|
+
)
|
|
64
|
+
.workers([
|
|
65
|
+
new Agent({ name: 'frontend-dev', instructions: 'Build UI components' }),
|
|
66
|
+
new Agent({ name: 'backend-dev', instructions: 'Build API endpoints' }),
|
|
67
|
+
new Agent({ name: 'tester', instructions: 'Write and run tests' }),
|
|
68
|
+
])
|
|
69
|
+
.hierarchical({
|
|
70
|
+
maxDelegations: 5,
|
|
71
|
+
requireApproval: false,
|
|
72
|
+
parallelExecution: true,
|
|
73
|
+
})
|
|
74
|
+
.build(cogitator);
|
|
25
75
|
|
|
26
|
-
const result = await swarm.run(
|
|
27
|
-
input: 'Build a
|
|
76
|
+
const result = await swarm.run({
|
|
77
|
+
input: 'Build a user authentication system',
|
|
28
78
|
});
|
|
29
79
|
```
|
|
30
80
|
|
|
31
|
-
###
|
|
81
|
+
### Round-Robin
|
|
82
|
+
|
|
83
|
+
Load-balanced rotation across agents:
|
|
84
|
+
|
|
85
|
+
```typescript
|
|
86
|
+
const swarm = new SwarmBuilder('support-team')
|
|
87
|
+
.strategy('round-robin')
|
|
88
|
+
.agents([
|
|
89
|
+
new Agent({ name: 'support-1', instructions: 'Handle customer queries' }),
|
|
90
|
+
new Agent({ name: 'support-2', instructions: 'Handle customer queries' }),
|
|
91
|
+
new Agent({ name: 'support-3', instructions: 'Handle customer queries' }),
|
|
92
|
+
])
|
|
93
|
+
.roundRobin({
|
|
94
|
+
maxRounds: 10,
|
|
95
|
+
skipUnavailable: true,
|
|
96
|
+
})
|
|
97
|
+
.build(cogitator);
|
|
98
|
+
```
|
|
99
|
+
|
|
100
|
+
### Consensus
|
|
101
|
+
|
|
102
|
+
Voting-based decisions with multiple agents:
|
|
103
|
+
|
|
104
|
+
```typescript
|
|
105
|
+
const swarm = new SwarmBuilder('review-board')
|
|
106
|
+
.strategy('consensus')
|
|
107
|
+
.agents([
|
|
108
|
+
new Agent({ name: 'reviewer-1', instructions: 'Review from security perspective' }),
|
|
109
|
+
new Agent({ name: 'reviewer-2', instructions: 'Review from performance perspective' }),
|
|
110
|
+
new Agent({ name: 'reviewer-3', instructions: 'Review from UX perspective' }),
|
|
111
|
+
])
|
|
112
|
+
.consensus({
|
|
113
|
+
votingMethod: 'majority',
|
|
114
|
+
minVotes: 2,
|
|
115
|
+
timeout: 30000,
|
|
116
|
+
tieBreaker: 'random',
|
|
117
|
+
})
|
|
118
|
+
.build(cogitator);
|
|
119
|
+
```
|
|
120
|
+
|
|
121
|
+
### Pipeline
|
|
122
|
+
|
|
123
|
+
Sequential processing stages:
|
|
124
|
+
|
|
125
|
+
```typescript
|
|
126
|
+
const swarm = new SwarmBuilder('content-pipeline')
|
|
127
|
+
.strategy('pipeline')
|
|
128
|
+
.pipeline({
|
|
129
|
+
stages: [
|
|
130
|
+
{ agent: new Agent({ name: 'researcher', instructions: 'Research the topic' }) },
|
|
131
|
+
{ agent: new Agent({ name: 'writer', instructions: 'Write the content' }) },
|
|
132
|
+
{ agent: new Agent({ name: 'editor', instructions: 'Edit and refine' }) },
|
|
133
|
+
{ agent: new Agent({ name: 'reviewer', instructions: 'Final review' }) },
|
|
134
|
+
],
|
|
135
|
+
stopOnError: true,
|
|
136
|
+
passContext: true,
|
|
137
|
+
})
|
|
138
|
+
.build(cogitator);
|
|
139
|
+
```
|
|
140
|
+
|
|
141
|
+
### Debate
|
|
32
142
|
|
|
33
143
|
Multiple perspectives with synthesis:
|
|
34
144
|
|
|
35
145
|
```typescript
|
|
36
146
|
const swarm = new SwarmBuilder('analysis-team')
|
|
37
147
|
.strategy('debate')
|
|
38
|
-
.agents([
|
|
39
|
-
|
|
148
|
+
.agents([
|
|
149
|
+
new Agent({ name: 'optimist', instructions: 'Present positive aspects' }),
|
|
150
|
+
new Agent({ name: 'skeptic', instructions: 'Challenge assumptions' }),
|
|
151
|
+
new Agent({ name: 'pragmatist', instructions: 'Focus on practicality' }),
|
|
152
|
+
])
|
|
153
|
+
.moderator(
|
|
154
|
+
new Agent({
|
|
155
|
+
name: 'moderator',
|
|
156
|
+
instructions: 'Guide discussion and synthesize conclusions',
|
|
157
|
+
})
|
|
158
|
+
)
|
|
159
|
+
.debate({
|
|
40
160
|
rounds: 3,
|
|
41
|
-
|
|
161
|
+
requireSynthesis: true,
|
|
162
|
+
maxTurnsPerRound: 2,
|
|
42
163
|
})
|
|
43
|
-
.build();
|
|
164
|
+
.build(cogitator);
|
|
44
165
|
```
|
|
45
166
|
|
|
46
|
-
###
|
|
167
|
+
### Auction
|
|
47
168
|
|
|
48
|
-
|
|
169
|
+
Bidding-based task assignment:
|
|
49
170
|
|
|
50
171
|
```typescript
|
|
51
|
-
const swarm = new SwarmBuilder('
|
|
52
|
-
.strategy('
|
|
53
|
-
.
|
|
54
|
-
{
|
|
55
|
-
{
|
|
56
|
-
{
|
|
172
|
+
const swarm = new SwarmBuilder('contractor-pool')
|
|
173
|
+
.strategy('auction')
|
|
174
|
+
.agents([
|
|
175
|
+
new Agent({ name: 'contractor-1', instructions: 'Bid based on expertise' }),
|
|
176
|
+
new Agent({ name: 'contractor-2', instructions: 'Bid based on expertise' }),
|
|
177
|
+
new Agent({ name: 'contractor-3', instructions: 'Bid based on expertise' }),
|
|
57
178
|
])
|
|
58
|
-
.
|
|
179
|
+
.auction({
|
|
180
|
+
biddingRounds: 2,
|
|
181
|
+
selectionCriteria: 'lowest',
|
|
182
|
+
allowNegotiation: true,
|
|
183
|
+
})
|
|
184
|
+
.build(cogitator);
|
|
185
|
+
```
|
|
186
|
+
|
|
187
|
+
---
|
|
188
|
+
|
|
189
|
+
## SwarmAssessor (Automatic Model Selection)
|
|
190
|
+
|
|
191
|
+
SwarmAssessor automatically analyzes tasks and matches optimal models to agent roles based on capabilities, cost, and availability.
|
|
192
|
+
|
|
193
|
+
### Basic Usage
|
|
194
|
+
|
|
195
|
+
```typescript
|
|
196
|
+
import { SwarmBuilder, createAssessor } from '@cogitator-ai/swarms';
|
|
197
|
+
|
|
198
|
+
const swarm = new SwarmBuilder('smart-team')
|
|
199
|
+
.strategy('hierarchical')
|
|
200
|
+
.supervisor(new Agent({ name: 'lead', instructions: '...' }))
|
|
201
|
+
.workers([
|
|
202
|
+
new Agent({ name: 'coder', instructions: '...' }),
|
|
203
|
+
new Agent({ name: 'analyst', instructions: '...' }),
|
|
204
|
+
])
|
|
205
|
+
.withAssessor({
|
|
206
|
+
mode: 'rules',
|
|
207
|
+
preferLocal: true,
|
|
208
|
+
minCapabilityMatch: 0.3,
|
|
209
|
+
maxCostPerRun: 0.5,
|
|
210
|
+
})
|
|
211
|
+
.build(cogitator);
|
|
212
|
+
|
|
213
|
+
// Models are automatically selected based on task requirements
|
|
214
|
+
const result = await swarm.run({ input: 'Complex coding task' });
|
|
215
|
+
|
|
216
|
+
// View what models were assigned
|
|
217
|
+
const assessment = swarm.getLastAssessment();
|
|
218
|
+
console.log(assessment?.assignments);
|
|
59
219
|
```
|
|
60
220
|
|
|
61
|
-
###
|
|
221
|
+
### Dry Run (Preview Assignments)
|
|
62
222
|
|
|
63
|
-
|
|
223
|
+
```typescript
|
|
224
|
+
const assessment = await swarm.dryRun({
|
|
225
|
+
input: 'Build a recommendation engine',
|
|
226
|
+
});
|
|
227
|
+
|
|
228
|
+
console.log('Task complexity:', assessment.taskAnalysis.complexity);
|
|
229
|
+
console.log('Estimated cost:', assessment.totalEstimatedCost);
|
|
230
|
+
|
|
231
|
+
for (const assignment of assessment.assignments) {
|
|
232
|
+
console.log(`${assignment.agentName}: ${assignment.assignedModel} (score: ${assignment.score})`);
|
|
233
|
+
}
|
|
234
|
+
```
|
|
235
|
+
|
|
236
|
+
### Assessor Configuration
|
|
237
|
+
|
|
238
|
+
```typescript
|
|
239
|
+
import { createAssessor, SwarmAssessor } from '@cogitator-ai/swarms';
|
|
240
|
+
|
|
241
|
+
const assessor = createAssessor({
|
|
242
|
+
mode: 'rules',
|
|
243
|
+
assessorModel: 'gpt-4o-mini',
|
|
244
|
+
preferLocal: true,
|
|
245
|
+
minCapabilityMatch: 0.3,
|
|
246
|
+
ollamaUrl: 'http://localhost:11434',
|
|
247
|
+
enabledProviders: ['ollama', 'openai', 'anthropic', 'google'],
|
|
248
|
+
cacheAssessments: true,
|
|
249
|
+
cacheTTL: 5 * 60 * 1000,
|
|
250
|
+
maxCostPerRun: 1.0,
|
|
251
|
+
});
|
|
252
|
+
```
|
|
253
|
+
|
|
254
|
+
### Model Suggestions
|
|
255
|
+
|
|
256
|
+
```typescript
|
|
257
|
+
const candidates = await assessor.suggestModels({
|
|
258
|
+
capabilities: ['code', 'reasoning'],
|
|
259
|
+
complexity: 'complex',
|
|
260
|
+
contextLength: 8000,
|
|
261
|
+
});
|
|
262
|
+
|
|
263
|
+
for (const model of candidates) {
|
|
264
|
+
console.log(`${model.modelId} (${model.provider}): score ${model.score}`);
|
|
265
|
+
}
|
|
266
|
+
```
|
|
267
|
+
|
|
268
|
+
### Assessor Components
|
|
269
|
+
|
|
270
|
+
| Component | Description |
|
|
271
|
+
| ---------------- | --------------------------------------------- |
|
|
272
|
+
| `TaskAnalyzer` | Analyzes task complexity and requirements |
|
|
273
|
+
| `ModelDiscovery` | Discovers available models from all providers |
|
|
274
|
+
| `ModelScorer` | Scores models against role requirements |
|
|
275
|
+
| `RoleMatcher` | Matches agents to optimal models |
|
|
276
|
+
|
|
277
|
+
---
|
|
278
|
+
|
|
279
|
+
## Agent Communication
|
|
280
|
+
|
|
281
|
+
### Message Bus
|
|
282
|
+
|
|
283
|
+
Agents can send direct messages and broadcasts:
|
|
284
|
+
|
|
285
|
+
```typescript
|
|
286
|
+
import { InMemoryMessageBus, createMessagingTools } from '@cogitator-ai/swarms';
|
|
287
|
+
|
|
288
|
+
const messageBus = new InMemoryMessageBus();
|
|
289
|
+
|
|
290
|
+
// Create tools for an agent
|
|
291
|
+
const tools = createMessagingTools(messageBus, 'agent-1');
|
|
292
|
+
|
|
293
|
+
// Tools available:
|
|
294
|
+
// - send_message: Send to specific agent
|
|
295
|
+
// - read_messages: Read incoming messages
|
|
296
|
+
// - broadcast_message: Send to all agents
|
|
297
|
+
// - reply_to_message: Reply to a specific message
|
|
298
|
+
```
|
|
299
|
+
|
|
300
|
+
### Blackboard (Shared State)
|
|
301
|
+
|
|
302
|
+
Agents can read/write shared state:
|
|
303
|
+
|
|
304
|
+
```typescript
|
|
305
|
+
import { InMemoryBlackboard, createBlackboardTools } from '@cogitator-ai/swarms';
|
|
306
|
+
|
|
307
|
+
const blackboard = new InMemoryBlackboard();
|
|
308
|
+
|
|
309
|
+
const tools = createBlackboardTools(blackboard, 'agent-1');
|
|
310
|
+
|
|
311
|
+
// Tools available:
|
|
312
|
+
// - read_blackboard: Read a section
|
|
313
|
+
// - write_blackboard: Write to a section
|
|
314
|
+
// - append_blackboard: Append to array section
|
|
315
|
+
// - list_blackboard_sections: List all sections
|
|
316
|
+
// - get_blackboard_history: Get change history
|
|
317
|
+
```
|
|
318
|
+
|
|
319
|
+
### Swarm Configuration with Communication
|
|
64
320
|
|
|
65
321
|
```typescript
|
|
66
322
|
const swarm = new SwarmBuilder('research-team')
|
|
67
323
|
.strategy('hierarchical')
|
|
68
324
|
.supervisor(supervisorAgent)
|
|
69
325
|
.workers([researcher1, researcher2])
|
|
70
|
-
.
|
|
71
|
-
|
|
326
|
+
.messaging({
|
|
327
|
+
enabled: true,
|
|
328
|
+
historySize: 100,
|
|
329
|
+
channels: ['findings', 'questions', 'progress'],
|
|
330
|
+
})
|
|
331
|
+
.blackboardConfig({
|
|
332
|
+
enabled: true,
|
|
333
|
+
sections: {
|
|
334
|
+
findings: [],
|
|
335
|
+
sources: [],
|
|
336
|
+
conclusions: '',
|
|
337
|
+
},
|
|
338
|
+
})
|
|
339
|
+
.build(cogitator);
|
|
340
|
+
```
|
|
341
|
+
|
|
342
|
+
---
|
|
343
|
+
|
|
344
|
+
## Built-in Swarm Tools
|
|
345
|
+
|
|
346
|
+
### All Tools at Once
|
|
347
|
+
|
|
348
|
+
```typescript
|
|
349
|
+
import { createSwarmTools, SwarmToolContext } from '@cogitator-ai/swarms';
|
|
350
|
+
|
|
351
|
+
const context: SwarmToolContext = {
|
|
352
|
+
coordinator,
|
|
353
|
+
blackboard,
|
|
354
|
+
messageBus,
|
|
355
|
+
events,
|
|
356
|
+
agentName: 'my-agent',
|
|
357
|
+
agentWeight: 1,
|
|
358
|
+
};
|
|
359
|
+
|
|
360
|
+
const tools = createSwarmTools(context);
|
|
361
|
+
// Returns 16 tools: messaging (4) + blackboard (5) + delegation (4) + voting (4)
|
|
362
|
+
```
|
|
363
|
+
|
|
364
|
+
### Strategy-Specific Tools
|
|
365
|
+
|
|
366
|
+
```typescript
|
|
367
|
+
import { createStrategyTools } from '@cogitator-ai/swarms';
|
|
368
|
+
|
|
369
|
+
// Get tools appropriate for the strategy
|
|
370
|
+
const tools = createStrategyTools('hierarchical', context);
|
|
371
|
+
// Returns: messaging + blackboard + delegation tools
|
|
372
|
+
|
|
373
|
+
const debateTools = createStrategyTools('debate', context);
|
|
374
|
+
// Returns: messaging + blackboard + voting tools
|
|
375
|
+
```
|
|
376
|
+
|
|
377
|
+
### Delegation Tools (Hierarchical)
|
|
378
|
+
|
|
379
|
+
```typescript
|
|
380
|
+
import { createDelegationTools } from '@cogitator-ai/swarms';
|
|
381
|
+
|
|
382
|
+
const tools = createDelegationTools(coordinator, blackboard, 'supervisor');
|
|
383
|
+
|
|
384
|
+
// delegate_task - Assign work to a worker
|
|
385
|
+
// check_progress - Monitor worker status
|
|
386
|
+
// request_revision - Ask for corrections
|
|
387
|
+
// list_workers - See available workers
|
|
388
|
+
```
|
|
389
|
+
|
|
390
|
+
### Voting Tools (Consensus/Debate)
|
|
391
|
+
|
|
392
|
+
```typescript
|
|
393
|
+
import { createVotingTools } from '@cogitator-ai/swarms';
|
|
394
|
+
|
|
395
|
+
const tools = createVotingTools(blackboard, events, 'voter-1', 1.0);
|
|
396
|
+
|
|
397
|
+
// cast_vote - Submit a vote
|
|
398
|
+
// get_votes - See current votes
|
|
399
|
+
// change_vote - Modify your vote
|
|
400
|
+
// get_consensus_status - Check if consensus reached
|
|
401
|
+
```
|
|
402
|
+
|
|
403
|
+
---
|
|
404
|
+
|
|
405
|
+
## Workflow Integration
|
|
406
|
+
|
|
407
|
+
Use swarms as nodes in DAG workflows.
|
|
408
|
+
|
|
409
|
+
### Basic Swarm Node
|
|
410
|
+
|
|
411
|
+
```typescript
|
|
412
|
+
import { WorkflowBuilder } from '@cogitator-ai/workflows';
|
|
413
|
+
import { swarmNode, SwarmNodeContext } from '@cogitator-ai/swarms';
|
|
414
|
+
|
|
415
|
+
const analysisSwarm = new SwarmBuilder('analysis')
|
|
416
|
+
.strategy('debate')
|
|
417
|
+
.agents([...])
|
|
418
|
+
.build(cogitator);
|
|
419
|
+
|
|
420
|
+
const workflow = new WorkflowBuilder('analysis-flow')
|
|
421
|
+
.addNode('analyze', swarmNode(analysisSwarm, {
|
|
422
|
+
inputMapper: (state) => state.document,
|
|
423
|
+
stateMapper: (result) => ({ analysis: result.output }),
|
|
424
|
+
}))
|
|
425
|
+
.build();
|
|
426
|
+
|
|
427
|
+
const result = await workflow.run({
|
|
428
|
+
cogitator,
|
|
429
|
+
input: { document: 'Analyze this document...' },
|
|
430
|
+
});
|
|
431
|
+
```
|
|
432
|
+
|
|
433
|
+
### Conditional Swarm Node
|
|
434
|
+
|
|
435
|
+
```typescript
|
|
436
|
+
import { conditionalSwarmNode } from '@cogitator-ai/swarms';
|
|
437
|
+
|
|
438
|
+
const workflow = new WorkflowBuilder('conditional-flow')
|
|
439
|
+
.addNode(
|
|
440
|
+
'expert-review',
|
|
441
|
+
conditionalSwarmNode(expertSwarm, (state) => state.needsExpertReview, {
|
|
442
|
+
stateMapper: (result) => ({ expertOpinion: result.output }),
|
|
443
|
+
})
|
|
444
|
+
)
|
|
445
|
+
.build();
|
|
446
|
+
```
|
|
447
|
+
|
|
448
|
+
### Parallel Swarms Node
|
|
449
|
+
|
|
450
|
+
```typescript
|
|
451
|
+
import { parallelSwarmsNode } from '@cogitator-ai/swarms';
|
|
452
|
+
|
|
453
|
+
const workflow = new WorkflowBuilder('parallel-analysis')
|
|
454
|
+
.addNode(
|
|
455
|
+
'multi-analyze',
|
|
456
|
+
parallelSwarmsNode(
|
|
457
|
+
[
|
|
458
|
+
{ swarm: technicalSwarm, key: 'technical' },
|
|
459
|
+
{ swarm: businessSwarm, key: 'business' },
|
|
460
|
+
{ swarm: legalSwarm, key: 'legal' },
|
|
461
|
+
],
|
|
462
|
+
(results) => ({
|
|
463
|
+
technicalAnalysis: results.technical.output,
|
|
464
|
+
businessAnalysis: results.business.output,
|
|
465
|
+
legalAnalysis: results.legal.output,
|
|
466
|
+
})
|
|
467
|
+
)
|
|
468
|
+
)
|
|
72
469
|
.build();
|
|
73
470
|
```
|
|
74
471
|
|
|
75
|
-
|
|
472
|
+
---
|
|
473
|
+
|
|
474
|
+
## Resource Tracking
|
|
475
|
+
|
|
476
|
+
Monitor and limit resource usage during swarm execution.
|
|
477
|
+
|
|
478
|
+
### Configuration
|
|
479
|
+
|
|
480
|
+
```typescript
|
|
481
|
+
const swarm = new SwarmBuilder('budget-conscious')
|
|
482
|
+
.strategy('hierarchical')
|
|
483
|
+
.supervisor(lead)
|
|
484
|
+
.workers(workers)
|
|
485
|
+
.resources({
|
|
486
|
+
tokenBudget: 100000,
|
|
487
|
+
costLimit: 5.0,
|
|
488
|
+
timeout: 300000,
|
|
489
|
+
})
|
|
490
|
+
.build(cogitator);
|
|
491
|
+
```
|
|
492
|
+
|
|
493
|
+
### ResourceTracker API
|
|
494
|
+
|
|
495
|
+
```typescript
|
|
496
|
+
import { ResourceTracker } from '@cogitator-ai/swarms';
|
|
497
|
+
|
|
498
|
+
const tracker = new ResourceTracker({
|
|
499
|
+
tokenBudget: 50000,
|
|
500
|
+
costLimit: 2.0,
|
|
501
|
+
timeout: 60000,
|
|
502
|
+
});
|
|
503
|
+
|
|
504
|
+
// Track agent runs
|
|
505
|
+
tracker.trackAgentRun('agent-1', runResult);
|
|
506
|
+
|
|
507
|
+
// Check budget
|
|
508
|
+
console.log('Within budget:', tracker.isWithinBudget());
|
|
509
|
+
console.log('Remaining:', tracker.getRemainingBudget());
|
|
510
|
+
|
|
511
|
+
// Get usage stats
|
|
512
|
+
const usage = tracker.getUsage();
|
|
513
|
+
console.log('Total tokens:', usage.totalTokens);
|
|
514
|
+
console.log('Total cost:', usage.totalCost);
|
|
515
|
+
console.log('Elapsed time:', usage.elapsedTime);
|
|
516
|
+
|
|
517
|
+
// Per-agent usage
|
|
518
|
+
const agentUsage = tracker.getAgentUsage('agent-1');
|
|
519
|
+
console.log('Agent tokens:', agentUsage?.tokens);
|
|
520
|
+
```
|
|
521
|
+
|
|
522
|
+
### Swarm Resource Usage
|
|
523
|
+
|
|
524
|
+
```typescript
|
|
525
|
+
const result = await swarm.run({ input: 'Task...' });
|
|
526
|
+
|
|
527
|
+
const usage = swarm.getResourceUsage();
|
|
528
|
+
console.log('Total tokens:', usage.totalTokens);
|
|
529
|
+
console.log('Total cost:', usage.totalCost);
|
|
530
|
+
|
|
531
|
+
for (const [agent, stats] of usage.agentUsage) {
|
|
532
|
+
console.log(`${agent}: ${stats.tokens} tokens, ${stats.runs} runs`);
|
|
533
|
+
}
|
|
534
|
+
```
|
|
535
|
+
|
|
536
|
+
---
|
|
537
|
+
|
|
538
|
+
## Circuit Breaker
|
|
539
|
+
|
|
540
|
+
Prevent cascading failures in swarm execution.
|
|
541
|
+
|
|
542
|
+
```typescript
|
|
543
|
+
import { CircuitBreaker } from '@cogitator-ai/swarms';
|
|
544
|
+
|
|
545
|
+
const breaker = new CircuitBreaker({
|
|
546
|
+
threshold: 5,
|
|
547
|
+
resetTimeout: 30000,
|
|
548
|
+
successThreshold: 2,
|
|
549
|
+
});
|
|
550
|
+
|
|
551
|
+
// Check before execution
|
|
552
|
+
if (breaker.canExecute()) {
|
|
553
|
+
try {
|
|
554
|
+
const result = await runTask();
|
|
555
|
+
breaker.recordSuccess();
|
|
556
|
+
} catch (error) {
|
|
557
|
+
breaker.recordFailure();
|
|
558
|
+
throw error;
|
|
559
|
+
}
|
|
560
|
+
} else {
|
|
561
|
+
console.log('Circuit is open, skipping execution');
|
|
562
|
+
}
|
|
563
|
+
|
|
564
|
+
// Monitor state changes
|
|
565
|
+
breaker.onStateChange((state) => {
|
|
566
|
+
console.log('Circuit state:', state); // 'closed' | 'open' | 'half-open'
|
|
567
|
+
});
|
|
568
|
+
|
|
569
|
+
// Reset manually
|
|
570
|
+
breaker.reset();
|
|
571
|
+
```
|
|
572
|
+
|
|
573
|
+
### Swarm Error Handling Configuration
|
|
574
|
+
|
|
575
|
+
```typescript
|
|
576
|
+
const swarm = new SwarmBuilder('resilient-team')
|
|
577
|
+
.strategy('hierarchical')
|
|
578
|
+
.supervisor(lead)
|
|
579
|
+
.workers(workers)
|
|
580
|
+
.errorHandling({
|
|
581
|
+
retryCount: 3,
|
|
582
|
+
retryDelay: 1000,
|
|
583
|
+
circuitBreaker: {
|
|
584
|
+
threshold: 5,
|
|
585
|
+
resetTimeout: 30000,
|
|
586
|
+
},
|
|
587
|
+
fallbackAgent: fallbackAgent,
|
|
588
|
+
})
|
|
589
|
+
.build(cogitator);
|
|
590
|
+
```
|
|
591
|
+
|
|
592
|
+
---
|
|
593
|
+
|
|
594
|
+
## Swarm Events
|
|
76
595
|
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
596
|
+
Subscribe to swarm lifecycle events.
|
|
597
|
+
|
|
598
|
+
```typescript
|
|
599
|
+
const swarm = new SwarmBuilder('monitored-team')
|
|
600
|
+
.strategy('hierarchical')
|
|
601
|
+
.supervisor(lead)
|
|
602
|
+
.workers(workers)
|
|
603
|
+
.build(cogitator);
|
|
604
|
+
|
|
605
|
+
// Subscribe to specific events
|
|
606
|
+
swarm.on('swarm:start', (event) => {
|
|
607
|
+
console.log('Swarm started:', event.swarmId);
|
|
608
|
+
});
|
|
609
|
+
|
|
610
|
+
swarm.on('agent:start', (event) => {
|
|
611
|
+
console.log(`Agent ${event.agentName} started`);
|
|
612
|
+
});
|
|
613
|
+
|
|
614
|
+
swarm.on('agent:complete', (event) => {
|
|
615
|
+
console.log(`Agent ${event.agentName} completed`);
|
|
616
|
+
});
|
|
617
|
+
|
|
618
|
+
swarm.on('swarm:complete', (event) => {
|
|
619
|
+
console.log('Swarm completed, agents used:', event.agentCount);
|
|
620
|
+
});
|
|
621
|
+
|
|
622
|
+
swarm.on('swarm:error', (event) => {
|
|
623
|
+
console.error('Swarm error:', event.error);
|
|
624
|
+
});
|
|
625
|
+
|
|
626
|
+
// Subscribe to all events
|
|
627
|
+
swarm.on('*', (event) => {
|
|
628
|
+
console.log('Event:', event);
|
|
629
|
+
});
|
|
630
|
+
|
|
631
|
+
// One-time subscription
|
|
632
|
+
swarm.once('swarm:complete', (event) => {
|
|
633
|
+
console.log('Finished!');
|
|
634
|
+
});
|
|
635
|
+
```
|
|
83
636
|
|
|
84
|
-
|
|
637
|
+
### Event Types
|
|
638
|
+
|
|
639
|
+
| Event | Description |
|
|
640
|
+
| ------------------- | ---------------------------- |
|
|
641
|
+
| `swarm:start` | Swarm execution started |
|
|
642
|
+
| `swarm:complete` | Swarm execution completed |
|
|
643
|
+
| `swarm:error` | Error during swarm execution |
|
|
644
|
+
| `swarm:paused` | Swarm paused |
|
|
645
|
+
| `swarm:resumed` | Swarm resumed |
|
|
646
|
+
| `swarm:aborted` | Swarm aborted |
|
|
647
|
+
| `swarm:reset` | Swarm reset |
|
|
648
|
+
| `agent:start` | Agent started execution |
|
|
649
|
+
| `agent:complete` | Agent completed execution |
|
|
650
|
+
| `agent:error` | Agent encountered error |
|
|
651
|
+
| `assessor:complete` | Model assessment completed |
|
|
652
|
+
| `message:sent` | Message sent between agents |
|
|
653
|
+
| `blackboard:write` | Blackboard updated |
|
|
654
|
+
| `vote:cast` | Vote cast in consensus |
|
|
655
|
+
|
|
656
|
+
---
|
|
657
|
+
|
|
658
|
+
## Swarm Control
|
|
659
|
+
|
|
660
|
+
### Pause and Resume
|
|
661
|
+
|
|
662
|
+
```typescript
|
|
663
|
+
const swarm = new SwarmBuilder('controllable')
|
|
664
|
+
.strategy('pipeline')
|
|
665
|
+
.pipeline({ stages: [...] })
|
|
666
|
+
.build(cogitator);
|
|
667
|
+
|
|
668
|
+
// Start execution
|
|
669
|
+
const resultPromise = swarm.run({ input: 'Process this...' });
|
|
670
|
+
|
|
671
|
+
// Pause mid-execution
|
|
672
|
+
setTimeout(() => {
|
|
673
|
+
swarm.pause();
|
|
674
|
+
console.log('Paused:', swarm.isPaused());
|
|
675
|
+
|
|
676
|
+
// Resume later
|
|
677
|
+
setTimeout(() => {
|
|
678
|
+
swarm.resume();
|
|
679
|
+
}, 5000);
|
|
680
|
+
}, 2000);
|
|
681
|
+
|
|
682
|
+
const result = await resultPromise;
|
|
683
|
+
```
|
|
684
|
+
|
|
685
|
+
### Abort
|
|
686
|
+
|
|
687
|
+
```typescript
|
|
688
|
+
const timeoutId = setTimeout(() => {
|
|
689
|
+
if (!swarm.isAborted()) {
|
|
690
|
+
swarm.abort();
|
|
691
|
+
console.log('Swarm aborted due to timeout');
|
|
692
|
+
}
|
|
693
|
+
}, 60000);
|
|
694
|
+
|
|
695
|
+
try {
|
|
696
|
+
const result = await swarm.run({ input: 'Task...' });
|
|
697
|
+
clearTimeout(timeoutId);
|
|
698
|
+
} catch (error) {
|
|
699
|
+
if (swarm.isAborted()) {
|
|
700
|
+
console.log('Task was aborted');
|
|
701
|
+
}
|
|
702
|
+
}
|
|
703
|
+
```
|
|
704
|
+
|
|
705
|
+
### Reset
|
|
706
|
+
|
|
707
|
+
```typescript
|
|
708
|
+
// Reset swarm state for a new run
|
|
709
|
+
swarm.reset();
|
|
710
|
+
|
|
711
|
+
// Run again with fresh state
|
|
712
|
+
const result = await swarm.run({ input: 'New task...' });
|
|
713
|
+
```
|
|
714
|
+
|
|
715
|
+
---
|
|
716
|
+
|
|
717
|
+
## Type Reference
|
|
718
|
+
|
|
719
|
+
### Core Types
|
|
720
|
+
|
|
721
|
+
```typescript
|
|
722
|
+
import type {
|
|
723
|
+
SwarmConfig,
|
|
724
|
+
SwarmRunOptions,
|
|
725
|
+
SwarmAgent,
|
|
726
|
+
SwarmAgentMetadata,
|
|
727
|
+
SwarmAgentState,
|
|
728
|
+
StrategyResult,
|
|
729
|
+
SwarmStrategy,
|
|
730
|
+
} from '@cogitator-ai/swarms';
|
|
731
|
+
```
|
|
732
|
+
|
|
733
|
+
### Strategy Types
|
|
734
|
+
|
|
735
|
+
```typescript
|
|
736
|
+
import type {
|
|
737
|
+
HierarchicalConfig,
|
|
738
|
+
RoundRobinConfig,
|
|
739
|
+
ConsensusConfig,
|
|
740
|
+
AuctionConfig,
|
|
741
|
+
PipelineConfig,
|
|
742
|
+
PipelineStage,
|
|
743
|
+
DebateConfig,
|
|
744
|
+
} from '@cogitator-ai/swarms';
|
|
745
|
+
```
|
|
746
|
+
|
|
747
|
+
### Communication Types
|
|
748
|
+
|
|
749
|
+
```typescript
|
|
750
|
+
import type {
|
|
751
|
+
MessageBus,
|
|
752
|
+
MessageBusConfig,
|
|
753
|
+
Blackboard,
|
|
754
|
+
BlackboardConfig,
|
|
755
|
+
BlackboardEntry,
|
|
756
|
+
SwarmMessage,
|
|
757
|
+
SwarmMessageType,
|
|
758
|
+
} from '@cogitator-ai/swarms';
|
|
759
|
+
```
|
|
760
|
+
|
|
761
|
+
### Assessor Types
|
|
762
|
+
|
|
763
|
+
```typescript
|
|
764
|
+
import type {
|
|
765
|
+
AssessorConfig,
|
|
766
|
+
AssessmentResult,
|
|
767
|
+
TaskRequirements,
|
|
768
|
+
RoleRequirements,
|
|
769
|
+
ModelAssignment,
|
|
770
|
+
ModelCandidate,
|
|
771
|
+
DiscoveredModel,
|
|
772
|
+
ScoredModel,
|
|
773
|
+
} from '@cogitator-ai/swarms';
|
|
774
|
+
```
|
|
775
|
+
|
|
776
|
+
### Event Types
|
|
777
|
+
|
|
778
|
+
```typescript
|
|
779
|
+
import type {
|
|
780
|
+
SwarmEventEmitter,
|
|
781
|
+
SwarmEventType,
|
|
782
|
+
SwarmEvent,
|
|
783
|
+
SwarmEventHandler,
|
|
784
|
+
} from '@cogitator-ai/swarms';
|
|
785
|
+
```
|
|
786
|
+
|
|
787
|
+
---
|
|
788
|
+
|
|
789
|
+
## Examples
|
|
790
|
+
|
|
791
|
+
### Research Team with Shared Knowledge
|
|
792
|
+
|
|
793
|
+
```typescript
|
|
794
|
+
const swarm = new SwarmBuilder('research-team')
|
|
795
|
+
.strategy('hierarchical')
|
|
796
|
+
.supervisor(
|
|
797
|
+
new Agent({
|
|
798
|
+
name: 'lead-researcher',
|
|
799
|
+
instructions: 'Coordinate research and synthesize findings',
|
|
800
|
+
})
|
|
801
|
+
)
|
|
802
|
+
.workers([
|
|
803
|
+
new Agent({
|
|
804
|
+
name: 'web-researcher',
|
|
805
|
+
instructions: 'Search and analyze web sources',
|
|
806
|
+
tools: [webSearchTool],
|
|
807
|
+
}),
|
|
808
|
+
new Agent({
|
|
809
|
+
name: 'data-analyst',
|
|
810
|
+
instructions: 'Analyze data and statistics',
|
|
811
|
+
tools: [calculatorTool],
|
|
812
|
+
}),
|
|
813
|
+
new Agent({
|
|
814
|
+
name: 'writer',
|
|
815
|
+
instructions: 'Write clear summaries',
|
|
816
|
+
}),
|
|
817
|
+
])
|
|
818
|
+
.messaging({ enabled: true })
|
|
819
|
+
.blackboardConfig({
|
|
820
|
+
enabled: true,
|
|
821
|
+
sections: { findings: [], sources: [], draft: '' },
|
|
822
|
+
})
|
|
823
|
+
.withAssessor({ preferLocal: true })
|
|
824
|
+
.build(cogitator);
|
|
825
|
+
|
|
826
|
+
const result = await swarm.run({
|
|
827
|
+
input: 'Research the impact of AI on job markets',
|
|
828
|
+
});
|
|
829
|
+
```
|
|
830
|
+
|
|
831
|
+
### Code Review Pipeline
|
|
832
|
+
|
|
833
|
+
```typescript
|
|
834
|
+
const swarm = new SwarmBuilder('code-review')
|
|
835
|
+
.strategy('pipeline')
|
|
836
|
+
.pipeline({
|
|
837
|
+
stages: [
|
|
838
|
+
{
|
|
839
|
+
agent: new Agent({
|
|
840
|
+
name: 'syntax-checker',
|
|
841
|
+
instructions: 'Check for syntax errors and style issues',
|
|
842
|
+
}),
|
|
843
|
+
},
|
|
844
|
+
{
|
|
845
|
+
agent: new Agent({
|
|
846
|
+
name: 'security-reviewer',
|
|
847
|
+
instructions: 'Check for security vulnerabilities',
|
|
848
|
+
}),
|
|
849
|
+
},
|
|
850
|
+
{
|
|
851
|
+
agent: new Agent({
|
|
852
|
+
name: 'performance-reviewer',
|
|
853
|
+
instructions: 'Check for performance issues',
|
|
854
|
+
}),
|
|
855
|
+
},
|
|
856
|
+
{
|
|
857
|
+
agent: new Agent({
|
|
858
|
+
name: 'summarizer',
|
|
859
|
+
instructions: 'Summarize all findings',
|
|
860
|
+
}),
|
|
861
|
+
},
|
|
862
|
+
],
|
|
863
|
+
stopOnError: false,
|
|
864
|
+
passContext: true,
|
|
865
|
+
})
|
|
866
|
+
.build(cogitator);
|
|
867
|
+
```
|
|
868
|
+
|
|
869
|
+
### Decision Making with Consensus
|
|
870
|
+
|
|
871
|
+
```typescript
|
|
872
|
+
const swarm = new SwarmBuilder('investment-committee')
|
|
873
|
+
.strategy('consensus')
|
|
874
|
+
.agents([
|
|
875
|
+
new Agent({ name: 'risk-analyst', instructions: 'Evaluate risks' }),
|
|
876
|
+
new Agent({ name: 'growth-analyst', instructions: 'Evaluate growth potential' }),
|
|
877
|
+
new Agent({ name: 'market-analyst', instructions: 'Evaluate market conditions' }),
|
|
878
|
+
])
|
|
879
|
+
.consensus({
|
|
880
|
+
votingMethod: 'weighted',
|
|
881
|
+
minVotes: 3,
|
|
882
|
+
weights: { 'risk-analyst': 1.5, 'growth-analyst': 1.0, 'market-analyst': 1.0 },
|
|
883
|
+
})
|
|
884
|
+
.build(cogitator);
|
|
885
|
+
|
|
886
|
+
const result = await swarm.run({
|
|
887
|
+
input: 'Should we invest in Company X?',
|
|
888
|
+
});
|
|
889
|
+
|
|
890
|
+
console.log('Decision:', result.output);
|
|
891
|
+
console.log('Vote breakdown:', result.metadata?.votes);
|
|
892
|
+
```
|
|
85
893
|
|
|
86
|
-
|
|
894
|
+
---
|
|
87
895
|
|
|
88
896
|
## License
|
|
89
897
|
|