@agentforge/patterns 0.1.0

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 ADDED
@@ -0,0 +1,489 @@
1
+ # @agentforge/patterns
2
+
3
+ Agent patterns (ReAct, Plan-Execute, Reflection, Multi-Agent) for the AgentForge framework.
4
+
5
+ ## Status
6
+
7
+ ✅ **Phase 3 Complete** - All Core Patterns Implemented
8
+
9
+ **100+ tests passing** | **Full TypeScript support** | **Comprehensive documentation**
10
+
11
+ ## Features
12
+
13
+ ### ✅ ReAct Pattern (Phase 3.1)
14
+
15
+ The ReAct (Reasoning and Action) pattern implements a thought-action-observation loop where the agent:
16
+ 1. **Thinks** about what to do next
17
+ 2. **Acts** by calling a tool or responding
18
+ 3. **Observes** the result
19
+ 4. **Repeats** until the task is complete
20
+
21
+ **Components**:
22
+ - **State Management** - Type-safe state with Zod schemas (10 tests)
23
+ - **Node Implementations** - Reasoning, action, and observation nodes (9 tests)
24
+ - **Agent Factory** - `createReActAgent()` function (10 tests)
25
+ - **Fluent Builder** - `ReActAgentBuilder` with method chaining (19 tests)
26
+ - **Integration Tests** - End-to-end scenarios (7 tests)
27
+
28
+ ### ✅ Plan-Execute Pattern (Phase 3.2)
29
+
30
+ The Plan-Execute pattern separates planning from execution for better performance on complex tasks:
31
+ 1. **Plan** - Create a structured, multi-step plan
32
+ 2. **Execute** - Execute each step of the plan
33
+ 3. **Replan** (optional) - Adjust the plan based on results
34
+ 4. **Finish** - Synthesize results into final response
35
+
36
+ **Features**:
37
+ - **Structured Planning** - Multi-step plan generation
38
+ - **Sequential & Parallel Execution** - Execute steps in order or parallel
39
+ - **Dependency Management** - Handle step dependencies
40
+ - **Adaptive Replanning** - Adjust plan based on results
41
+ - **Progress Tracking** - Monitor execution progress
42
+
43
+ ### ✅ Reflection Pattern (Phase 3.3)
44
+
45
+ The Reflection pattern implements iterative self-improvement through generation, critique, and revision:
46
+ 1. **Generate** - Create initial response
47
+ 2. **Reflect** - Critique the response
48
+ 3. **Revise** - Improve based on critique
49
+ 4. **Repeat** - Continue until quality threshold met
50
+
51
+ **Features**:
52
+ - **Iterative Improvement** - Multiple revision cycles
53
+ - **Self-Critique** - Agent evaluates its own output
54
+ - **Quality Focus** - Optimizes for output quality
55
+ - **Flexible Criteria** - Custom reflection criteria
56
+ - **Configurable Iterations** - Control refinement depth
57
+
58
+ ### ✅ Multi-Agent Pattern (Phase 3.4)
59
+
60
+ The Multi-Agent pattern coordinates multiple specialized agents for complex tasks:
61
+ 1. **Supervisor** - Routes tasks to appropriate workers
62
+ 2. **Workers** - Execute specialized tasks
63
+ 3. **Aggregator** - Combines results from workers
64
+ 4. **Routing** - Intelligent task distribution
65
+
66
+ **Features**:
67
+ - **Specialized Agents** - Workers with distinct capabilities
68
+ - **Flexible Routing** - LLM-based, skill-based, rule-based, round-robin, load-balanced
69
+ - **Parallel Execution** - Workers can run concurrently
70
+ - **Result Aggregation** - Combine outputs intelligently
71
+ - **Scalable Coordination** - Add workers dynamically
72
+
73
+ ## Installation
74
+
75
+ ```bash
76
+ pnpm add @agentforge/patterns @agentforge/core
77
+ ```
78
+
79
+ ## Quick Start
80
+
81
+ ### ReAct Agent
82
+
83
+ Simple reasoning and action loop:
84
+
85
+ ```typescript
86
+ import { ReActAgentBuilder } from '@agentforge/patterns';
87
+ import { toolBuilder, ToolCategory } from '@agentforge/core';
88
+ import { ChatOpenAI } from '@langchain/openai';
89
+ import { z } from 'zod';
90
+
91
+ // Create a tool
92
+ const calculatorTool = toolBuilder()
93
+ .name('calculator')
94
+ .description('Perform arithmetic operations')
95
+ .category(ToolCategory.UTILITY)
96
+ .schema(
97
+ z.object({
98
+ operation: z.enum(['add', 'subtract', 'multiply', 'divide']),
99
+ a: z.number(),
100
+ b: z.number(),
101
+ })
102
+ )
103
+ .implement(async ({ operation, a, b }) => {
104
+ switch (operation) {
105
+ case 'add': return a + b;
106
+ case 'subtract': return a - b;
107
+ case 'multiply': return a * b;
108
+ case 'divide': return a / b;
109
+ }
110
+ })
111
+ .build();
112
+
113
+ // Create the agent
114
+ const agent = new ReActAgentBuilder()
115
+ .withLLM(new ChatOpenAI({ model: 'gpt-4' }))
116
+ .withTools([calculatorTool])
117
+ .withMaxIterations(10)
118
+ .build();
119
+
120
+ // Use the agent
121
+ const result = await agent.invoke({
122
+ messages: [{ role: 'user', content: 'What is 15 * 7?' }],
123
+ });
124
+
125
+ console.log(result.response); // "The result is 105"
126
+ ```
127
+
128
+ ### Plan-Execute Agent
129
+
130
+ Structured planning and execution:
131
+
132
+ ```typescript
133
+ import { createPlanExecuteAgent } from '@agentforge/patterns';
134
+ import { ChatOpenAI } from '@langchain/openai';
135
+ import { z } from 'zod';
136
+
137
+ // Create tools
138
+ const searchTool = {
139
+ name: 'search',
140
+ description: 'Search for information',
141
+ schema: z.object({ query: z.string() }),
142
+ execute: async ({ query }) => {
143
+ // Search implementation
144
+ return { results: [...] };
145
+ },
146
+ };
147
+
148
+ const analyzeTool = {
149
+ name: 'analyze',
150
+ description: 'Analyze data',
151
+ schema: z.object({ data: z.any() }),
152
+ execute: async ({ data }) => {
153
+ // Analysis implementation
154
+ return { insights: [...] };
155
+ },
156
+ };
157
+
158
+ // Create the agent
159
+ const agent = createPlanExecuteAgent({
160
+ planner: {
161
+ llm: new ChatOpenAI({ model: 'gpt-4' }),
162
+ maxSteps: 5,
163
+ },
164
+ executor: {
165
+ tools: [searchTool, analyzeTool],
166
+ parallel: true, // Enable parallel execution
167
+ },
168
+ replanner: {
169
+ llm: new ChatOpenAI({ model: 'gpt-4' }),
170
+ replanThreshold: 0.7, // Replan if confidence < 0.7
171
+ },
172
+ });
173
+
174
+ // Use the agent
175
+ const result = await agent.invoke({
176
+ input: 'Research AI developments and analyze trends',
177
+ });
178
+
179
+ console.log(result.plan); // The generated plan
180
+ console.log(result.pastSteps); // Executed steps
181
+ console.log(result.response); // Final synthesized response
182
+ ```
183
+
184
+ ### Reflection Agent
185
+
186
+ Iterative self-improvement:
187
+
188
+ ```typescript
189
+ import { createReflectionAgent } from '@agentforge/patterns';
190
+ import { ChatOpenAI } from '@langchain/openai';
191
+
192
+ // Create the agent
193
+ const agent = createReflectionAgent({
194
+ generator: {
195
+ llm: new ChatOpenAI({ model: 'gpt-4' }),
196
+ systemPrompt: 'You are a professional writer. Create high-quality content.',
197
+ },
198
+ reflector: {
199
+ llm: new ChatOpenAI({ model: 'gpt-4' }),
200
+ systemPrompt: 'Critique the content for clarity, engagement, and professionalism.',
201
+ },
202
+ maxIterations: 3,
203
+ verbose: true,
204
+ });
205
+
206
+ // Use the agent
207
+ const result = await agent.invoke({
208
+ messages: [{ role: 'user', content: 'Write a blog post about AI' }],
209
+ });
210
+
211
+ console.log(result.reflections); // All critiques
212
+ console.log(result.response); // Final refined response
213
+ ```
214
+
215
+ ### Multi-Agent System
216
+
217
+ Coordinate specialized agents:
218
+
219
+ ```typescript
220
+ import { MultiAgentSystemBuilder } from '@agentforge/patterns';
221
+ import { ChatOpenAI } from '@langchain/openai';
222
+
223
+ const llm = new ChatOpenAI({ model: 'gpt-4' });
224
+
225
+ // Create builder
226
+ const builder = new MultiAgentSystemBuilder({
227
+ supervisor: {
228
+ llm,
229
+ strategy: 'skill-based', // or 'llm-based', 'round-robin', etc.
230
+ },
231
+ aggregator: { llm },
232
+ });
233
+
234
+ // Register specialized workers
235
+ builder.registerWorkers([
236
+ {
237
+ id: 'tech_support',
238
+ name: 'Tech Support',
239
+ description: 'Handles technical issues',
240
+ capabilities: {
241
+ skills: ['technical', 'troubleshooting', 'debugging'],
242
+ tools: ['diagnostic', 'troubleshoot'],
243
+ available: true,
244
+ },
245
+ llm,
246
+ tools: [diagnosticTool, troubleshootTool],
247
+ },
248
+ {
249
+ id: 'billing_support',
250
+ name: 'Billing Support',
251
+ description: 'Handles billing inquiries',
252
+ capabilities: {
253
+ skills: ['billing', 'payments', 'refunds'],
254
+ tools: ['account_check', 'refund_process'],
255
+ available: true,
256
+ },
257
+ llm,
258
+ tools: [checkAccountTool, processRefundTool],
259
+ },
260
+ ]);
261
+
262
+ // Build and use the system
263
+ const system = builder.build();
264
+
265
+ const result = await system.invoke({
266
+ input: 'My app keeps crashing and I need a refund',
267
+ });
268
+
269
+ console.log(result.response); // Aggregated response
270
+ ```
271
+
272
+ ## Documentation
273
+
274
+ ### Guides
275
+ - [ReAct Agent Guide](./docs/react-agent-guide.md) - Comprehensive ReAct usage guide
276
+ - [Plan-Execute Pattern Guide](./docs/plan-execute-pattern.md) - Comprehensive Plan-Execute guide
277
+ - [Reflection Pattern Guide](./docs/reflection-pattern.md) - Comprehensive Reflection guide
278
+ - [Multi-Agent Pattern Guide](./docs/multi-agent-pattern.md) - Comprehensive Multi-Agent guide
279
+ - [Pattern Comparison Guide](./docs/pattern-comparison.md) - Choose the right pattern
280
+
281
+ ### Implementation Details
282
+ - [Phase 3.1 Summary](./docs/phase-3.1.4-summary.md) - ReAct implementation details
283
+
284
+ ### Examples
285
+ - [ReAct Examples](./examples/react/) - ReAct pattern examples
286
+ - [Plan-Execute Examples](./examples/plan-execute/) - Plan-Execute pattern examples
287
+ - [Reflection Examples](./examples/reflection/) - Reflection pattern examples
288
+ - [Multi-Agent Examples](./examples/multi-agent/) - Multi-Agent pattern examples
289
+
290
+ ## API Reference
291
+
292
+ ### ReAct Pattern
293
+
294
+ ```typescript
295
+ import {
296
+ ReActAgentBuilder,
297
+ createReActAgent,
298
+ createReActAgentBuilder,
299
+ } from '@agentforge/patterns';
300
+ ```
301
+
302
+ **Builder API**:
303
+ - `withLLM(llm)` - Set the language model (required)
304
+ - `withTools(tools)` - Set tools array or registry (required)
305
+ - `withSystemPrompt(prompt)` - Set system prompt (optional)
306
+ - `withMaxIterations(max)` - Set max iterations (optional, default: 10)
307
+ - `withReturnIntermediateSteps(value)` - Include reasoning steps (optional)
308
+ - `withStopCondition(fn)` - Custom termination logic (optional)
309
+ - `withVerbose(value)` - Enable verbose logging (optional)
310
+ - `withNodeNames(names)` - Customize node names (optional)
311
+ - `build()` - Build the agent
312
+
313
+ ### Plan-Execute Pattern
314
+
315
+ ```typescript
316
+ import {
317
+ createPlanExecuteAgent,
318
+ createPlannerNode,
319
+ createExecutorNode,
320
+ createReplannerNode,
321
+ createFinisherNode,
322
+ } from '@agentforge/patterns';
323
+ ```
324
+
325
+ **Main API**:
326
+ - `createPlanExecuteAgent(config)` - Create a complete Plan-Execute agent
327
+
328
+ **Configuration**:
329
+ ```typescript
330
+ {
331
+ planner: {
332
+ llm: BaseChatModel, // LLM for planning
333
+ systemPrompt?: string, // Custom planning prompt
334
+ maxSteps?: number, // Max steps in plan (default: 10)
335
+ includeToolDescriptions?: boolean,
336
+ },
337
+ executor: {
338
+ tools: Tool[], // Available tools
339
+ llm?: BaseChatModel, // Optional LLM for sub-tasks
340
+ parallel?: boolean, // Enable parallel execution
341
+ stepTimeout?: number, // Timeout per step (ms)
342
+ maxParallelSteps?: number, // Max concurrent steps
343
+ },
344
+ replanner?: {
345
+ llm: BaseChatModel, // LLM for replanning
346
+ replanThreshold?: number, // Confidence threshold (0-1)
347
+ systemPrompt?: string, // Custom replanning prompt
348
+ },
349
+ maxIterations?: number, // Max planning iterations
350
+ returnIntermediateSteps?: boolean,
351
+ verbose?: boolean,
352
+ }
353
+ ```
354
+
355
+ **Node Creators** (for custom workflows):
356
+ - `createPlannerNode(config)` - Create planner node
357
+ - `createExecutorNode(config)` - Create executor node
358
+ - `createReplannerNode(config)` - Create replanner node
359
+ - `createFinisherNode()` - Create finisher node
360
+
361
+ ### Reflection Pattern
362
+
363
+ ```typescript
364
+ import {
365
+ createReflectionAgent,
366
+ createGeneratorNode,
367
+ createReflectorNode,
368
+ createReviserNode,
369
+ } from '@agentforge/patterns';
370
+ ```
371
+
372
+ **Main API**:
373
+ - `createReflectionAgent(config)` - Create a complete Reflection agent
374
+
375
+ **Configuration**:
376
+ ```typescript
377
+ {
378
+ generator: {
379
+ llm: BaseChatModel, // LLM for generation
380
+ systemPrompt?: string, // Custom generation prompt
381
+ },
382
+ reflector: {
383
+ llm: BaseChatModel, // LLM for reflection
384
+ systemPrompt?: string, // Custom reflection prompt
385
+ criteria?: string[], // Reflection criteria
386
+ },
387
+ maxIterations?: number, // Max reflection cycles (default: 3)
388
+ qualityThreshold?: number, // Quality score threshold (0-1)
389
+ returnIntermediateSteps?: boolean,
390
+ verbose?: boolean,
391
+ }
392
+ ```
393
+
394
+ **Node Creators** (for custom workflows):
395
+ - `createGeneratorNode(config)` - Create generator node
396
+ - `createReflectorNode(config)` - Create reflector node
397
+ - `createReviserNode(config)` - Create reviser node
398
+
399
+ ### Multi-Agent Pattern
400
+
401
+ ```typescript
402
+ import {
403
+ createMultiAgentSystem,
404
+ registerWorkers,
405
+ createSupervisorNode,
406
+ createWorkerNode,
407
+ createAggregatorNode,
408
+ } from '@agentforge/patterns';
409
+ ```
410
+
411
+ **Main API**:
412
+ - `createMultiAgentSystem(config)` - Create a complete Multi-Agent system
413
+ - `registerWorkers(system, workers)` - Register workers with the system
414
+
415
+ **Configuration**:
416
+ ```typescript
417
+ {
418
+ supervisor: {
419
+ llm: BaseChatModel, // LLM for routing decisions
420
+ routingStrategy: RoutingStrategy, // Routing strategy
421
+ systemPrompt?: string, // Custom supervisor prompt
422
+ },
423
+ workers: WorkerConfig[], // Worker configurations
424
+ aggregator: {
425
+ llm: BaseChatModel, // LLM for aggregation
426
+ systemPrompt?: string, // Custom aggregator prompt
427
+ },
428
+ maxIterations?: number, // Max coordination iterations
429
+ verbose?: boolean,
430
+ }
431
+ ```
432
+
433
+ **Routing Strategies**:
434
+ - `'llm-based'` - LLM analyzes task and selects worker
435
+ - `'skill-based'` - Match task to worker capabilities
436
+ - `'round-robin'` - Distribute tasks evenly
437
+ - `'load-balanced'` - Route to least busy worker
438
+ - Custom rule-based routing
439
+
440
+ **Worker Configuration**:
441
+ ```typescript
442
+ {
443
+ name: string, // Unique worker identifier
444
+ description: string, // Worker description
445
+ capabilities: string[], // Worker capabilities/skills
446
+ tools: Tool[], // Available tools
447
+ systemPrompt?: string, // Worker-specific prompt
448
+ }
449
+ ```
450
+
451
+ **Node Creators** (for custom workflows):
452
+ - `createSupervisorNode(config)` - Create supervisor node
453
+ - `createWorkerNode(config)` - Create worker node
454
+ - `createAggregatorNode(config)` - Create aggregator node
455
+
456
+ ## Pattern Selection Guide
457
+
458
+ | Pattern | Best For | Key Strength | Main Limitation |
459
+ |---------|----------|--------------|-----------------|
460
+ | **ReAct** | Exploration, flexibility | Dynamic adaptation | Sequential only |
461
+ | **Plan-Execute** | Structured workflows | Parallel execution | Requires planning |
462
+ | **Reflection** | Quality-critical outputs | Iterative improvement | Slow, expensive |
463
+ | **Multi-Agent** | Specialized tasks | Coordinated expertise | High complexity |
464
+
465
+ See the [Pattern Comparison Guide](./docs/pattern-comparison.md) for detailed guidance.
466
+
467
+ ## Development
468
+
469
+ ```bash
470
+ # Install dependencies
471
+ pnpm install
472
+
473
+ # Build the package
474
+ pnpm build
475
+
476
+ # Run tests
477
+ pnpm test
478
+
479
+ # Run tests with coverage
480
+ pnpm test:coverage
481
+
482
+ # Type check
483
+ pnpm typecheck
484
+ ```
485
+
486
+ ## License
487
+
488
+ MIT
489
+