dank-ai 1.0.1 → 1.0.3

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 CHANGED
@@ -1,1331 +1,107 @@
1
- # 🚀 Dank Agent Service
1
+ # my-interactive-project
2
2
 
3
- **Docker-based AI Agent Orchestration Platform**
3
+ A Dank AI agent project with modern event handling and Docker orchestration.
4
4
 
5
- Dank is a powerful Node.js service that allows you to define, deploy, and manage AI agents using Docker containers. Each agent runs in its own isolated environment with configurable resources, LLM providers, and custom handlers.
5
+ ## Features
6
6
 
7
- ## Features
7
+ - 🤖 **AI Agents**: Powered by multiple LLM providers (OpenAI, Anthropic, Google AI)
8
+ - 🐳 **Docker Integration**: Containerized agents with automatic management
9
+ - 📡 **Event System**: Real-time event handling for prompts, responses, and tools
10
+ - 🔧 **Auto-Detection**: Automatically enables features based on usage
11
+ - 📊 **Monitoring**: Built-in logging and status monitoring
8
12
 
9
- - **🤖 Multi-LLM Support**: OpenAI, Anthropic, Cohere, Ollama, and custom providers
10
- - **🐳 Docker Orchestration**: Isolated agent containers with resource management
11
- - **⚡ Easy Configuration**: Define agents with simple JavaScript configuration
12
- - **📊 Real-time Monitoring**: Built-in health checks and status monitoring
13
- - **🔧 Flexible Handlers**: Custom event handlers for agent outputs and errors
14
- - **🎯 CLI Interface**: Powerful command-line tools for agent management
13
+ ## Quick Start
15
14
 
16
- ## 🚀 Quick Start
15
+ 1. **Install dependencies:**
16
+ ```bash
17
+ npm install
18
+ ```
17
19
 
18
- ### Prerequisites
19
- Before you begin, make sure you have:
20
- - **Node.js 16+** installed
21
- - **Docker Desktop** or **Docker Engine** (will be installed automatically if missing)
22
- - **API keys** for your chosen LLM provider(s)
20
+ 2. **Set up environment:**
21
+ ```bash
22
+ cp .env.example .env
23
+ # Edit .env with your API keys
24
+ ```
23
25
 
24
- > **🆕 Auto-Docker Installation**: Dank will automatically detect, install, and start Docker if it's not available on your system. No manual setup required!
26
+ 3. **Configure your agents:**
27
+ Edit `dank.config.js` to define your agents and their capabilities.
25
28
 
26
- ### 1. Install Dank globally
27
- ```bash
28
- npm install -g dank-ai
29
- ```
30
-
31
- ### 2. Initialize a new project
32
- ```bash
33
- # Create and navigate to your project directory
34
- mkdir my-agent-project
35
- cd my-agent-project
36
-
37
- # Initialize Dank project
38
- dank init my-agent-project
39
- ```
40
-
41
- This creates:
42
- ```
43
- my-agent-project/
44
- ├── dank.config.js # Your agent configuration
45
- ├── agents/ # Custom agent code (optional)
46
- │ └── example-agent.js
47
- └── .dank/ # Generated files
48
- └── project.yaml
49
- ```
50
-
51
- ### 3. Set up environment variables
52
- Create a `.env` file or export environment variables:
53
-
54
- ```bash
55
- # For OpenAI
56
- export OPENAI_API_KEY="your-openai-api-key"
57
-
58
- # For Anthropic
59
- export ANTHROPIC_API_KEY="your-anthropic-api-key"
60
-
61
- # For Cohere
62
- export COHERE_API_KEY="your-cohere-api-key"
63
- ```
64
-
65
- ### 4. Configure your agents
66
- Edit `dank.config.js` to define your agents:
67
-
68
- ```javascript
69
- const { createAgent } = require('dank');
70
-
71
- module.exports = {
72
- name: 'my-agent-project',
73
-
74
- agents: [
75
- createAgent('assistant')
76
- .setLLM('openai', {
77
- apiKey: process.env.OPENAI_API_KEY,
78
- model: 'gpt-3.5-turbo',
79
- temperature: 0.7
80
- })
81
- .setPrompt('You are a helpful assistant that responds with enthusiasm!')
82
- .setResources({
83
- memory: '512m',
84
- cpu: 1
85
- })
86
- .addHandler('output', (data) => {
87
- console.log('Assistant says:', data);
88
- })
89
- ]
90
- };
91
- ```
29
+ 4. **Start your agents:**
30
+ ```bash
31
+ npm start
32
+ # or
33
+ dank run
34
+ ```
92
35
 
93
- ### 5. Build the base Docker image
94
- ```bash
95
- # First time setup - build the base image
96
- dank build --base
97
- ```
98
-
99
- ### 6. Start your agents
100
- ```bash
101
- # Start all agents
102
- dank run
103
-
104
- # Or run in detached mode (background)
105
- dank run --detached
106
- ```
107
-
108
- ### 7. Monitor your agents
109
- ```bash
110
- # Check agent status
111
- dank status
36
+ ## Available Commands
112
37
 
113
- # Watch status in real-time
114
- dank status --watch
38
+ - `npm start` - Start all agents
39
+ - `npm run dev` - Start in development mode
40
+ - `npm run stop` - Stop all agents
41
+ - `npm run status` - Check agent status
42
+ - `npm run logs` - View agent logs
43
+ - `npm run build` - Build agent images
44
+ - `npm run clean` - Clean up containers and images
115
45
 
116
- # View agent logs
117
- dank logs assistant
46
+ ## Event Handlers
118
47
 
119
- # Follow logs in real-time
120
- dank logs assistant --follow
121
- ```
122
-
123
- ## 📋 CLI Commands
124
-
125
- ### Core Commands
126
- ```bash
127
- dank run # Start all defined agents
128
- dank status # Show agent status
129
- dank stop [agents...] # Stop specific agents
130
- dank stop --all # Stop all agents
131
- dank logs [agent] # View agent logs
132
- ```
133
-
134
- ### Management Commands
135
- ```bash
136
- dank init [name] # Initialize new project
137
- dank build # Build Docker images
138
- dank clean # Clean up Docker resources
139
- ```
140
-
141
- ### Advanced Options
142
- ```bash
143
- dank run --detached # Run in background
144
- dank run --build # Force rebuild images
145
- dank status --watch # Live status monitoring
146
- dank logs --follow # Follow log output
147
- ```
148
-
149
- ## 🤖 Agent Configuration
150
-
151
- ### Basic Agent Setup
152
- ```javascript
153
- const agent = createAgent('my-agent')
154
- .setLLM('openai', {
155
- apiKey: process.env.OPENAI_API_KEY,
156
- model: 'gpt-4',
157
- temperature: 0.8
158
- })
159
- .setPrompt('Your system prompt here')
160
- .setResources({
161
- memory: '1g',
162
- cpu: 2,
163
- timeout: 60000
164
- });
165
- ```
48
+ This project includes examples of the three main event types:
166
49
 
167
- ### Supported LLM Providers
50
+ ### 1. Direct Prompting Events (`request_output`)
51
+ Handle LLM interactions and modify prompts/responses:
168
52
 
169
- #### OpenAI
170
53
  ```javascript
171
- .setLLM('openai', {
172
- apiKey: 'your-api-key',
173
- model: 'gpt-4',
174
- temperature: 0.7,
175
- maxTokens: 1000
176
- })
177
- ```
178
-
179
- #### Anthropic
180
- ```javascript
181
- .setLLM('anthropic', {
182
- apiKey: 'your-api-key',
183
- model: 'claude-3-sonnet-20240229',
184
- maxTokens: 1000
185
- })
186
- ```
187
-
188
- #### Ollama (Local)
189
- ```javascript
190
- .setLLM('ollama', {
191
- baseURL: 'http://localhost:11434',
192
- model: 'llama2'
193
- })
194
- ```
195
-
196
- #### Custom Provider
197
- ```javascript
198
- .setLLM('custom', {
199
- baseURL: 'https://api.your-provider.com',
200
- apiKey: 'your-key',
201
- model: 'your-model'
202
- })
203
- ```
204
-
205
- ### Event Handlers
206
-
207
- Dank provides a comprehensive event system with three main sources of events. Each event handler follows specific naming patterns for maximum flexibility and control.
208
-
209
- #### 🎯 **Event Handler Patterns**
210
-
211
- ##### **1. Direct Prompting Events** (`request_output`)
212
- Events triggered when agents receive and respond to direct prompts via WebSocket or HTTP:
213
-
214
- ```javascript
215
- agent
216
- // Main LLM response event
217
- .addHandler('request_output', (data) => {
218
- console.log('LLM Response:', {
219
- prompt: data.prompt, // Original prompt
220
- finalPrompt: data.finalPrompt, // Modified prompt (if changed)
221
- response: data.response, // LLM response
222
- conversationId: data.conversationId,
223
- processingTime: data.processingTime,
224
- promptModified: data.promptModified, // Boolean: was prompt modified?
225
- usage: data.usage,
226
- model: data.model
227
- });
228
- })
229
-
230
- // Lifecycle events with modification capabilities
231
- .addHandler('request_output:start', (data) => {
232
- console.log('Processing prompt:', data.conversationId);
233
- console.log('Original prompt:', data.prompt);
234
-
235
- // ✨ MODIFY PROMPT: Return modified data to change the prompt sent to LLM
236
- const enhancedPrompt = `Context: You are a helpful assistant. Please be concise and friendly.\n\nUser Question: ${data.prompt}`;
237
-
238
- return {
239
- prompt: enhancedPrompt // This will replace the original prompt
240
- };
241
- })
242
-
243
- .addHandler('request_output:end', (data) => {
244
- console.log('Completed in:', data.processingTime + 'ms');
245
- console.log('Original response:', data.response.substring(0, 50) + '...');
246
-
247
- // ✨ MODIFY RESPONSE: Return modified data to change the response sent to caller
248
- const enhancedResponse = `${data.response}\n\n---\n💡 This response was generated by Dank Framework`;
249
-
250
- return {
251
- response: enhancedResponse // This will replace the original response
252
- };
253
- })
254
-
255
- .addHandler('request_output:error', (data) => {
256
- console.error('Prompt processing failed:', data.error);
257
- });
258
- ```
259
-
260
- **🔄 Event Modification Capabilities:**
261
-
262
- - **`request_output:start`**: Can modify the prompt before it's sent to the LLM by returning an object with a `prompt` property
263
- - **`request_output:end`**: Can modify the response before it's sent back to the caller by returning an object with a `response` property
264
- - **Event Data**: All events include both original and final values, plus modification flags for tracking changes
265
-
266
- **⏱️ Event Flow Timeline:**
267
-
268
- 1. **`request_output:start`** → Fires when prompt is received
269
- - Can modify prompt before LLM processing
270
- - Contains: `{ prompt, conversationId, context, timestamp }`
271
-
272
- 2. **LLM Processing** → The (potentially modified) prompt is sent to the LLM
273
-
274
- 3. **`request_output`** → Fires after LLM responds successfully
275
- - Contains: `{ prompt, finalPrompt, response, conversationId, promptModified, ... }`
276
-
277
- 4. **`request_output:end`** → Fires after `request_output`, before sending to caller
278
- - Can modify response before returning to client
279
- - Contains: `{ prompt, finalPrompt, response, conversationId, promptModified, success, ... }`
280
-
281
- 5. **Response Sent** → The (potentially modified) response is sent back to the caller
282
-
283
- **💡 Practical Examples:**
284
-
285
- ```javascript
286
- // Example 1: Add context and formatting to prompts
287
54
  .addHandler('request_output:start', (data) => {
288
- // Add system context and format the user's question
289
- const enhancedPrompt = `System: You are a helpful AI assistant. Be concise and professional.
290
-
291
- User Question: ${data.prompt}
292
-
293
- Please provide a clear, helpful response.`;
294
-
295
- return { prompt: enhancedPrompt };
55
+ // Modify the prompt before sending to LLM
56
+ return { prompt: `Enhanced: ${data.prompt}` };
296
57
  })
297
58
 
298
- // Example 2: Add metadata and branding to responses
299
59
  .addHandler('request_output:end', (data) => {
300
- // Add footer with metadata and branding
301
- const brandedResponse = `${data.response}
302
-
303
- ---
304
- 🤖 Generated by Dank Framework Agent
305
- ⏱️ Processing time: ${data.processingTime}ms
306
- 🆔 Conversation: ${data.conversationId}`;
307
-
308
- return { response: brandedResponse };
309
- })
310
-
311
- // Example 3: Log and analyze all interactions
312
- .addHandler('request_output', (data) => {
313
- // Log for analytics
314
- console.log('Interaction logged:', {
315
- originalPrompt: data.prompt,
316
- modifiedPrompt: data.finalPrompt,
317
- wasModified: data.promptModified,
318
- responseLength: data.response.length,
319
- model: data.model,
320
- usage: data.usage
321
- });
60
+ // Modify the response before sending back
61
+ return { response: `${data.response} [Enhanced by Dank]` };
322
62
  })
323
63
  ```
324
64
 
325
- ##### **2. Tool Events** (`tool:*`)
326
- Events triggered by tool usage, following the pattern `tool:<tool-name>:<action>:<specifics>`:
327
-
328
- ```javascript
329
- agent
330
- // HTTP Server Tool Events
331
- .addHandler('tool:http-server:*', (data) => {
332
- // Listen to ALL HTTP server events
333
- console.log('HTTP Activity:', data.type, data.method, data.path);
334
- })
335
-
336
- .addHandler('tool:http-server:call', (data) => {
337
- // All incoming HTTP requests
338
- console.log('Request:', data.method, data.path, data.body);
339
- })
340
-
341
- .addHandler('tool:http-server:response', (data) => {
342
- // All HTTP responses
343
- console.log('Response:', data.statusCode, data.processingTime);
344
- })
345
-
346
- .addHandler('tool:http-server:call:post', (data) => {
347
- // Only POST requests
348
- console.log('POST Request:', data.path, data.body);
349
- })
350
-
351
- .addHandler('tool:http-server:response:get', (data) => {
352
- // Only GET responses
353
- console.log('GET Response:', data.path, data.responseData);
354
- })
355
-
356
- .addHandler('tool:http-server:error', (data) => {
357
- // HTTP server errors
358
- console.error('HTTP Error:', data.error);
359
- });
360
- ```
361
-
362
- **Tool Event Pattern Structure:**
363
- - `tool:<tool-name>:*` - All events for a specific tool
364
- - `tool:<tool-name>:call` - Tool invocation/input events
365
- - `tool:<tool-name>:response` - Tool output/result events
366
- - `tool:<tool-name>:call:<method>` - Specific method calls (e.g., POST, GET)
367
- - `tool:<tool-name>:response:<method>` - Specific method responses
368
- - `tool:<tool-name>:error` - Tool-specific errors
369
-
370
- ##### **3. System Events** (Legacy/System)
371
- Traditional system-level events:
65
+ ### 2. HTTP API Events (`tool:http-server`)
66
+ Handle HTTP requests and responses:
372
67
 
373
68
  ```javascript
374
- agent
375
- .addHandler('output', (data) => {
376
- console.log('General output:', data);
377
- })
378
-
379
- .addHandler('error', (error) => {
380
- console.error('System error:', error);
381
- })
382
-
383
- .addHandler('heartbeat', () => {
384
- console.log('Agent heartbeat');
385
- })
386
-
387
- .addHandler('start', () => {
388
- console.log('Agent started');
389
- })
390
-
391
- .addHandler('stop', () => {
392
- console.log('Agent stopped');
393
- });
394
- ```
395
-
396
- #### 🔥 **Advanced Event Patterns**
397
-
398
- **Wildcard Matching:**
399
- ```javascript
400
- // Listen to all tool events
401
- .addHandler('tool:*', (data) => {
402
- console.log('Any tool activity:', data);
69
+ .addHandler('tool:http-server:call', (data) => {
70
+ console.log('HTTP request received:', data.method, data.path);
403
71
  })
404
72
 
405
- // Listen to all HTTP responses
406
- .addHandler('tool:http-server:response:*', (data) => {
407
- console.log('Any HTTP response:', data);
408
- })
409
-
410
- // Listen to all request outputs
411
- .addHandler('request_output:*', (data) => {
412
- console.log('Any request event:', data);
73
+ .addHandler('tool:http-server:response', (data) => {
74
+ console.log('HTTP response sent:', data.statusCode);
413
75
  })
414
76
  ```
415
77
 
416
- **Multiple Handlers:**
417
- ```javascript
418
- // Multiple handlers for the same event
419
- agent
420
- .addHandler('request_output', (data) => {
421
- // Log to console
422
- console.log('Response:', data.response);
423
- })
424
- .addHandler('request_output', (data) => {
425
- // Save to database
426
- saveToDatabase(data);
427
- })
428
- .addHandler('request_output', (data) => {
429
- // Send to analytics
430
- trackAnalytics(data);
431
- });
432
- ```
433
-
434
- #### 📊 **Event Data Structures**
435
-
436
- **Request Output Event Data:**
437
- ```javascript
438
- {
439
- prompt: "User's input prompt",
440
- response: "LLM's response",
441
- conversationId: "unique-conversation-id",
442
- context: { protocol: "websocket", clientId: "..." },
443
- usage: { total_tokens: 150, prompt_tokens: 50, completion_tokens: 100 },
444
- model: "gpt-3.5-turbo",
445
- processingTime: 1250,
446
- timestamp: "2024-01-15T10:30:00.000Z"
447
- }
448
- ```
449
-
450
- **Tool HTTP Event Data:**
451
- ```javascript
452
- {
453
- requestId: "unique-request-id",
454
- method: "POST",
455
- path: "/api/chat",
456
- headers: { "content-type": "application/json" },
457
- body: { message: "Hello" },
458
- query: {},
459
- params: {},
460
- statusCode: 200,
461
- responseData: { response: "Hi there!" },
462
- processingTime: 45,
463
- timestamp: "2024-01-15T10:30:00.000Z"
464
- }
465
- ```
466
-
467
- #### 🎛️ **Communication Method Control**
468
-
469
- Each communication method can be enabled/disabled independently:
470
-
471
- ```javascript
472
- createAgent('flexible-agent')
473
- // Enable only direct prompting
474
- .enableDirectPrompting({ protocol: 'websocket' })
475
- .disableHttpApi()
476
- .enableEventHandlers()
477
-
478
- // Listen to direct prompting events only
479
- .addHandler('request_output', (data) => {
480
- console.log('WebSocket response:', data.response);
481
- })
482
-
483
- // HTTP events won't fire since HTTP is disabled
484
- .addHandler('tool:http-server:*', (data) => {
485
- console.log('This will never execute');
486
- });
487
- ```
488
-
489
- ### Resource Management
490
-
491
- Configure container resources:
78
+ ### 3. System Events
79
+ Handle agent lifecycle and errors:
492
80
 
493
81
  ```javascript
494
- .setResources({
495
- memory: '512m', // Memory limit (512m, 1g, etc.)
496
- cpu: 1, // CPU allocation (0.5, 1, 2, etc.)
497
- timeout: 30000, // Request timeout in ms
498
- maxRestarts: 3 // Max container restarts
82
+ .addHandler('output', (data) => {
83
+ console.log('Agent output:', data);
499
84
  })
500
- ```
501
-
502
- ## 🏗️ Project Structure
503
85
 
86
+ .addHandler('error', (error) => {
87
+ console.error('Agent error:', error);
88
+ })
504
89
  ```
505
- my-project/
506
- ├── dank.config.js # Agent configuration
507
- ├── agents/ # Custom agent code (optional)
508
- │ └── example-agent.js
509
- └── .dank/ # Generated files
510
- ├── project.yaml # Project state
511
- └── logs/ # Agent logs
512
- ```
513
-
514
- ## 📦 Package Exports
515
-
516
- When you install Dank via npm, you can import the following:
517
-
518
- ```javascript
519
- const {
520
- createAgent, // Convenience function to create agents
521
- DankAgent, // Main agent class
522
- DankProject, // Project management class
523
- AgentConfig, // Configuration utilities
524
- SUPPORTED_LLMS, // List of supported LLM providers
525
- DEFAULT_CONFIG // Default configuration values
526
- } = require("dank");
527
- ```
528
-
529
- ## 📋 Example Files
530
-
531
- The `examples/` directory contains two configuration files:
532
-
533
- - **`dank.config.js`** - Local development example (uses `../lib/index.js`)
534
- - **`dank.config.template.js`** - Production template (uses `require("dank")`)
535
-
536
- ### For Local Development
537
- ```bash
538
- # Use the example file directly
539
- dank run --config example/dank.config.js
540
- ```
541
-
542
- ### For Production Use
543
- ```bash
544
- # 1. Copy the template to your project
545
- cp example/dank.config.template.js ./dank.config.js
546
-
547
- # 2. Install dank as a dependency
548
- npm install dank-ai
549
-
550
- # 3. The template already uses the correct import
551
- # const { createAgent } = require("dank");
552
-
553
- # 4. Run your agents
554
- dank run
555
- ```
556
-
557
- ## 🐳 Docker Architecture
558
-
559
- Dank uses a layered Docker approach:
560
-
561
- 1. **Base Image** (`dank-agent-base`): Common runtime with Node.js, LLM clients
562
- 2. **Agent Images**: Extend base image with agent-specific code
563
- 3. **Containers**: Running instances with resource limits and networking
564
-
565
- ### Container Features
566
- - **Isolated Environments**: Each agent runs in its own container
567
- - **Resource Limits**: Memory and CPU constraints per agent
568
- - **Health Monitoring**: Built-in health checks and status reporting
569
- - **Automatic Restarts**: Container restart policies for reliability
570
- - **Logging**: Centralized log collection and viewing
571
-
572
- ### 🚀 Automatic Docker Management
573
-
574
- Dank automatically handles Docker installation and startup for you:
575
-
576
- #### **Auto-Detection & Installation**
577
- When you run any Dank command, it will:
578
- 1. **Check if Docker is installed** - Runs `docker --version` to detect installation
579
- 2. **Install Docker if missing** - Automatically installs Docker for your platform:
580
- - **macOS**: Uses Homebrew to install Docker Desktop
581
- - **Linux**: Installs Docker CE via apt package manager
582
- - **Windows**: Uses Chocolatey to install Docker Desktop
583
- 3. **Start Docker if stopped** - Automatically starts Docker service
584
- 4. **Wait for availability** - Ensures Docker is ready before proceeding
585
-
586
- #### **Platform-Specific Installation**
587
-
588
- **macOS:**
589
- ```bash
590
- # Dank will automatically run:
591
- brew install --cask docker
592
- open -a Docker
593
- ```
594
-
595
- **Linux (Ubuntu/Debian):**
596
- ```bash
597
- # Dank will automatically run:
598
- sudo apt-get update
599
- sudo apt-get install -y docker-ce docker-ce-cli containerd.io
600
- sudo systemctl start docker
601
- sudo systemctl enable docker
602
- sudo usermod -aG docker $USER
603
- ```
604
-
605
- **Windows:**
606
- ```bash
607
- # Dank will automatically run:
608
- choco install docker-desktop -y
609
- start "" "C:\Program Files\Docker\Docker\Docker Desktop.exe"
610
- ```
611
-
612
- #### **Manual Fallback**
613
- If automatic installation fails, Dank will provide clear instructions:
614
- ```bash
615
- # Example output when manual installation is needed
616
- ❌ Docker installation failed: Homebrew not found
617
- 💡 Please install Docker Desktop manually from:
618
- https://www.docker.com/products/docker-desktop/
619
- ```
620
-
621
- #### **Status Messages**
622
- Dank provides clear feedback during the process:
623
- ```bash
624
- 🔍 Checking Docker availability...
625
- 📦 Docker is not installed. Installing Docker...
626
- 🖥️ Installing Docker Desktop for macOS...
627
- ⏳ Installing Docker Desktop via Homebrew...
628
- ✅ Docker installation completed
629
- 🚀 Starting Docker Desktop...
630
- ⏳ Waiting for Docker to become available...
631
- ✅ Docker is now available
632
- 🐳 Docker connection established
633
- ```
634
-
635
- ## 💼 Using Dank in Your Project
636
-
637
- ### Step-by-Step Integration Guide
638
-
639
- #### 1. Project Setup
640
- ```bash
641
- # In your existing project directory
642
- npm install -g dank-ai
643
-
644
- # Initialize Dank configuration
645
- dank init
646
-
647
- # This creates dank.config.js in your current directory
648
- ```
649
-
650
- #### 2. Basic Agent Configuration
651
- Start with a simple agent configuration in `dank.config.js`:
652
-
653
- ```javascript
654
- const { createAgent } = require('dank');
655
-
656
- module.exports = {
657
- name: 'my-project',
658
-
659
- agents: [
660
- // Simple assistant agent
661
- createAgent('helper')
662
- .setLLM('openai', {
663
- apiKey: process.env.OPENAI_API_KEY,
664
- model: 'gpt-3.5-turbo'
665
- })
666
- .setPrompt('You are a helpful assistant.')
667
- .addHandler('output', console.log)
668
- ]
669
- };
670
- ```
671
-
672
- #### 3. Multi-Agent Setup
673
- Configure multiple specialized agents:
674
-
675
- ```javascript
676
- const { createAgent } = require('dank');
677
-
678
- module.exports = {
679
- name: 'multi-agent-system',
680
-
681
- agents: [
682
- // Customer service agent
683
- createAgent('customer-service')
684
- .setLLM('openai', {
685
- apiKey: process.env.OPENAI_API_KEY,
686
- model: 'gpt-3.5-turbo',
687
- temperature: 0.7
688
- })
689
- .setPrompt(`
690
- You are a friendly customer service representative.
691
- - Be helpful and professional
692
- - Resolve customer issues quickly
693
- - Escalate complex problems appropriately
694
- `)
695
- .setResources({ memory: '512m', cpu: 1 })
696
- .addHandler('output', (data) => {
697
- console.log('[Customer Service]:', data);
698
- // Add your business logic here
699
- }),
700
-
701
- // Data analyst agent
702
- createAgent('analyst')
703
- .setLLM('openai', {
704
- apiKey: process.env.OPENAI_API_KEY,
705
- model: 'gpt-4',
706
- temperature: 0.3
707
- })
708
- .setPrompt(`
709
- You are a data analyst expert.
710
- - Analyze trends and patterns
711
- - Provide statistical insights
712
- - Create actionable recommendations
713
- `)
714
- .setResources({ memory: '1g', cpu: 2 })
715
- .addHandler('output', (data) => {
716
- console.log('[Analyst]:', data);
717
- // Save analysis results to database
718
- }),
719
-
720
- // Content creator agent
721
- createAgent('content-creator')
722
- .setLLM('anthropic', {
723
- apiKey: process.env.ANTHROPIC_API_KEY,
724
- model: 'claude-3-sonnet-20240229'
725
- })
726
- .setPrompt(`
727
- You are a creative content writer.
728
- - Write engaging, original content
729
- - Adapt tone to target audience
730
- - Follow brand guidelines
731
- `)
732
- .setResources({ memory: '512m', cpu: 1 })
733
- .addHandler('output', (data) => {
734
- console.log('[Content Creator]:', data);
735
- // Process and publish content
736
- })
737
- ]
738
- };
739
- ```
740
-
741
- ### 🎯 Common Use Cases
742
-
743
- #### Use Case 1: Customer Support Automation
744
- ```javascript
745
- createAgent('support-bot')
746
- .setLLM('openai', {
747
- apiKey: process.env.OPENAI_API_KEY,
748
- model: 'gpt-3.5-turbo'
749
- })
750
- .setPrompt(`
751
- You are a customer support specialist for [Your Company].
752
-
753
- Guidelines:
754
- - Always be polite and helpful
755
- - For technical issues, provide step-by-step solutions
756
- - If you cannot resolve an issue, escalate to human support
757
- - Use the customer's name when available
758
-
759
- Knowledge Base:
760
- - Product features: [list your features]
761
- - Common issues: [list common problems and solutions]
762
- - Contact info: support@yourcompany.com
763
- `)
764
- .addHandler('output', (response) => {
765
- // Send response back to customer via your chat system
766
- sendToCustomer(response);
767
- })
768
- .addHandler('error', (error) => {
769
- // Fallback to human support
770
- escalateToHuman(error);
771
- });
772
- ```
773
-
774
- #### Use Case 2: Content Generation Pipeline
775
- ```javascript
776
- const contentAgents = [
777
- // Research agent
778
- createAgent('researcher')
779
- .setLLM('openai', { model: 'gpt-4' })
780
- .setPrompt('Research and gather information on given topics')
781
- .addHandler('output', (research) => {
782
- // Pass research to writer agent
783
- triggerContentCreation(research);
784
- }),
785
-
786
- // Writer agent
787
- createAgent('writer')
788
- .setLLM('anthropic', { model: 'claude-3-sonnet' })
789
- .setPrompt('Write engaging blog posts based on research data')
790
- .addHandler('output', (article) => {
791
- // Save draft and notify editor
792
- saveDraft(article);
793
- notifyEditor(article);
794
- }),
795
-
796
- // SEO optimizer agent
797
- createAgent('seo-optimizer')
798
- .setLLM('openai', { model: 'gpt-3.5-turbo' })
799
- .setPrompt('Optimize content for SEO and readability')
800
- .addHandler('output', (optimizedContent) => {
801
- // Publish optimized content
802
- publishContent(optimizedContent);
803
- })
804
- ];
805
- ```
806
-
807
- #### Use Case 3: Data Analysis Workflow
808
- ```javascript
809
- createAgent('data-processor')
810
- .setLLM('openai', {
811
- apiKey: process.env.OPENAI_API_KEY,
812
- model: 'gpt-4',
813
- temperature: 0.1 // Low temperature for consistent analysis
814
- })
815
- .setPrompt(`
816
- You are a data analyst. Analyze the provided data and:
817
- 1. Identify key trends and patterns
818
- 2. Calculate important metrics
819
- 3. Provide actionable insights
820
- 4. Format results as JSON
821
- `)
822
- .setResources({
823
- memory: '2g', // More memory for data processing
824
- cpu: 2, // More CPU for complex calculations
825
- timeout: 120000 // Longer timeout for large datasets
826
- })
827
- .addHandler('output', (analysis) => {
828
- try {
829
- const results = JSON.parse(analysis);
830
- // Store results in database
831
- saveAnalysisResults(results);
832
- // Generate reports
833
- generateReport(results);
834
- // Send alerts if thresholds are met
835
- checkAlerts(results);
836
- } catch (error) {
837
- console.error('Failed to parse analysis:', error);
838
- }
839
- });
840
- ```
841
-
842
- ### 🔧 Advanced Configuration
843
-
844
- #### Custom Agent Code
845
- For complex logic, create custom agent files in the `agents/` directory:
846
-
847
- ```javascript
848
- // agents/custom-agent.js
849
- module.exports = {
850
- async main(llmClient, handlers) {
851
- console.log('Custom agent starting...');
852
-
853
- // Your custom agent logic
854
- setInterval(async () => {
855
- try {
856
- // Make LLM request
857
- const response = await llmClient.chat.completions.create({
858
- model: 'gpt-3.5-turbo',
859
- messages: [
860
- { role: 'system', content: 'You are a helpful assistant' },
861
- { role: 'user', content: 'Generate a daily report' }
862
- ]
863
- });
864
-
865
- // Trigger output handlers
866
- const outputHandlers = handlers.get('output') || [];
867
- outputHandlers.forEach(handler =>
868
- handler(response.choices[0].message.content)
869
- );
870
-
871
- } catch (error) {
872
- // Trigger error handlers
873
- const errorHandlers = handlers.get('error') || [];
874
- errorHandlers.forEach(handler => handler(error));
875
- }
876
- }, 60000); // Run every minute
877
- },
878
-
879
- // Define custom handlers
880
- handlers: {
881
- output: [
882
- (data) => console.log('Custom output:', data)
883
- ],
884
- error: [
885
- (error) => console.error('Custom error:', error)
886
- ]
887
- }
888
- };
889
- ```
890
-
891
- #### Environment-Specific Configuration
892
- ```javascript
893
- // dank.config.js
894
- const { createAgent } = require('dank');
895
-
896
- const isDevelopment = process.env.NODE_ENV === 'development';
897
- const isProduction = process.env.NODE_ENV === 'production';
898
-
899
- module.exports = {
900
- name: 'my-project',
901
-
902
- agents: [
903
- createAgent('main-agent')
904
- .setLLM('openai', {
905
- apiKey: process.env.OPENAI_API_KEY,
906
- model: isDevelopment ? 'gpt-3.5-turbo' : 'gpt-4',
907
- temperature: isDevelopment ? 0.9 : 0.7
908
- })
909
- .setResources({
910
- memory: isDevelopment ? '256m' : '1g',
911
- cpu: isDevelopment ? 0.5 : 2
912
- })
913
- .addHandler('output', (data) => {
914
- if (isDevelopment) {
915
- console.log('DEV:', data);
916
- } else {
917
- // Production logging
918
- logger.info('Agent output', { data });
919
- }
920
- })
921
- ]
922
- };
923
- ```
924
-
925
- ### 🔧 Advanced Usage
926
-
927
- #### Environment Variables
928
- ```bash
929
- export OPENAI_API_KEY="your-key"
930
- export ANTHROPIC_API_KEY="your-key"
931
- export LOG_LEVEL="debug"
932
- export DOCKER_HOST="unix:///var/run/docker.sock"
933
- export NODE_ENV="production"
934
- ```
935
-
936
- #### Integration with Existing Applications
937
- ```javascript
938
- // In your existing Node.js application
939
- const { spawn } = require('child_process');
940
-
941
- // Start Dank agents programmatically
942
- function startAgents() {
943
- const dankProcess = spawn('dank', ['run', '--detached'], {
944
- stdio: 'inherit',
945
- env: { ...process.env, NODE_ENV: 'production' }
946
- });
947
-
948
- dankProcess.on('close', (code) => {
949
- console.log(`Dank agents exited with code ${code}`);
950
- });
951
-
952
- return dankProcess;
953
- }
954
-
955
- // Stop agents gracefully
956
- function stopAgents() {
957
- spawn('dank', ['stop', '--all'], { stdio: 'inherit' });
958
- }
959
-
960
- // Check agent status
961
- async function getAgentStatus() {
962
- return new Promise((resolve) => {
963
- const statusProcess = spawn('dank', ['status', '--json'], {
964
- stdio: ['pipe', 'pipe', 'pipe']
965
- });
966
-
967
- let output = '';
968
- statusProcess.stdout.on('data', (data) => {
969
- output += data.toString();
970
- });
971
-
972
- statusProcess.on('close', () => {
973
- try {
974
- resolve(JSON.parse(output));
975
- } catch {
976
- resolve(null);
977
- }
978
- });
979
- });
980
- }
981
- ```
982
-
983
- ### 🚨 Troubleshooting
984
-
985
- #### Common Issues and Solutions
986
-
987
- **1. Docker Connection Issues**
988
- ```bash
989
- # Error: Cannot connect to Docker daemon
990
- # Solution: Dank will automatically handle this!
991
-
992
- # If automatic installation fails, manual steps:
993
- docker --version
994
- docker ps
995
-
996
- # On macOS/Windows: Start Docker Desktop manually
997
- # On Linux: Start Docker service
998
- sudo systemctl start docker
999
- ```
1000
-
1001
- **1a. Docker Installation Issues**
1002
- ```bash
1003
- # If automatic installation fails, try manual installation:
1004
-
1005
- # macOS (with Homebrew):
1006
- brew install --cask docker
1007
- open -a Docker
1008
-
1009
- # Linux (Ubuntu/Debian):
1010
- sudo apt-get update
1011
- sudo apt-get install -y docker-ce docker-ce-cli containerd.io
1012
- sudo systemctl start docker
1013
- sudo usermod -aG docker $USER
1014
-
1015
- # Windows (with Chocolatey):
1016
- choco install docker-desktop -y
1017
- # Then start Docker Desktop from Start Menu
1018
- ```
1019
-
1020
- **2. API Key Issues**
1021
- ```bash
1022
- # Error: Invalid API key
1023
- # Solution: Check your environment variables
1024
- echo $OPENAI_API_KEY
1025
-
1026
- # Set the key properly
1027
- export OPENAI_API_KEY="sk-your-actual-key-here"
1028
-
1029
- # Or create a .env file in your project
1030
- echo "OPENAI_API_KEY=sk-your-actual-key-here" > .env
1031
- ```
1032
-
1033
- **3. Base Image Not Found**
1034
- ```bash
1035
- # Error: Base image 'dank-agent-base' not found
1036
- # Solution: Build the base image first
1037
- dank build --base
1038
- ```
1039
-
1040
- **4. Container Resource Issues**
1041
- ```bash
1042
- # Error: Container exits with code 137 (out of memory)
1043
- # Solution: Increase memory allocation
1044
- createAgent('my-agent')
1045
- .setResources({
1046
- memory: '1g', // Increase from 512m to 1g
1047
- cpu: 2
1048
- })
1049
- ```
1050
-
1051
- **5. Agent Not Starting**
1052
- ```bash
1053
- # Check agent logs for detailed error information
1054
- dank logs agent-name
1055
-
1056
- # Check container status
1057
- docker ps -f name=dank-
1058
-
1059
- # View Docker logs directly
1060
- docker logs container-id
1061
- ```
1062
-
1063
- ### 💡 Best Practices
1064
-
1065
- #### 1. Resource Management
1066
- ```javascript
1067
- // Good: Appropriate resource allocation
1068
- createAgent('light-agent')
1069
- .setResources({
1070
- memory: '256m', // Light tasks
1071
- cpu: 0.5
1072
- });
1073
-
1074
- createAgent('heavy-agent')
1075
- .setResources({
1076
- memory: '2g', // Heavy processing
1077
- cpu: 2,
1078
- timeout: 120000 // Longer timeout
1079
- });
1080
- ```
1081
-
1082
- #### 2. Error Handling
1083
- ```javascript
1084
- // Good: Comprehensive error handling
1085
- createAgent('robust-agent')
1086
- .addHandler('error', (error) => {
1087
- console.error('Agent error:', error.message);
1088
-
1089
- // Log to monitoring system
1090
- logError(error);
1091
-
1092
- // Send alert if critical
1093
- if (error.type === 'CRITICAL') {
1094
- sendAlert(error);
1095
- }
1096
-
1097
- // Implement retry logic
1098
- scheduleRetry(error.context);
1099
- })
1100
- .addHandler('output', (data) => {
1101
- try {
1102
- processOutput(data);
1103
- } catch (error) {
1104
- console.error('Output processing failed:', error);
1105
- }
1106
- });
1107
- ```
1108
-
1109
- #### 3. Environment Configuration
1110
- ```javascript
1111
- // Good: Environment-specific settings
1112
- const config = {
1113
- development: {
1114
- model: 'gpt-3.5-turbo',
1115
- memory: '256m',
1116
- logLevel: 'debug'
1117
- },
1118
- production: {
1119
- model: 'gpt-4',
1120
- memory: '1g',
1121
- logLevel: 'info'
1122
- }
1123
- };
1124
-
1125
- const env = process.env.NODE_ENV || 'development';
1126
- const settings = config[env];
1127
-
1128
- createAgent('environment-aware')
1129
- .setLLM('openai', {
1130
- model: settings.model,
1131
- temperature: 0.7
1132
- })
1133
- .setResources({
1134
- memory: settings.memory
1135
- });
1136
- ```
1137
-
1138
- #### 4. Monitoring and Logging
1139
- ```javascript
1140
- // Good: Structured logging
1141
- createAgent('monitored-agent')
1142
- .addHandler('output', (data) => {
1143
- logger.info('Agent output', {
1144
- agent: 'monitored-agent',
1145
- timestamp: new Date().toISOString(),
1146
- data: data.substring(0, 100) // Truncate for logs
1147
- });
1148
- })
1149
- .addHandler('error', (error) => {
1150
- logger.error('Agent error', {
1151
- agent: 'monitored-agent',
1152
- error: error.message,
1153
- stack: error.stack
1154
- });
1155
- })
1156
- .addHandler('start', () => {
1157
- logger.info('Agent started', { agent: 'monitored-agent' });
1158
- });
1159
- ```
1160
-
1161
- #### 5. Security Considerations
1162
- ```javascript
1163
- // Good: Secure configuration
1164
- createAgent('secure-agent')
1165
- .setLLM('openai', {
1166
- apiKey: process.env.OPENAI_API_KEY, // Never hardcode keys
1167
- model: 'gpt-3.5-turbo'
1168
- })
1169
- .setPrompt(`
1170
- You are a helpful assistant.
1171
-
1172
- IMPORTANT SECURITY RULES:
1173
- - Never reveal API keys or sensitive information
1174
- - Don't execute system commands
1175
- - Validate all inputs before processing
1176
- - Don't access external URLs unless explicitly allowed
1177
- `)
1178
- .addHandler('output', (data) => {
1179
- // Sanitize output before logging
1180
- const sanitized = sanitizeOutput(data);
1181
- console.log(sanitized);
1182
- });
1183
- ```
1184
-
1185
- ### 📊 Performance Optimization
1186
-
1187
- #### 1. Resource Tuning
1188
- ```bash
1189
- # Monitor resource usage
1190
- dank status --watch
1191
-
1192
- # Check container stats
1193
- docker stats $(docker ps -f name=dank- -q)
1194
-
1195
- # Optimize based on usage patterns
1196
- ```
1197
-
1198
- #### 2. Parallel Agent Management
1199
- ```javascript
1200
- // Good: Balanced agent distribution
1201
- module.exports = {
1202
- agents: [
1203
- // CPU-intensive agents
1204
- createAgent('analyzer').setResources({ cpu: 2, memory: '1g' }),
1205
-
1206
- // Memory-intensive agents
1207
- createAgent('processor').setResources({ cpu: 1, memory: '2g' }),
1208
-
1209
- // Light agents
1210
- createAgent('notifier').setResources({ cpu: 0.5, memory: '256m' })
1211
- ]
1212
- };
1213
- ```
1214
-
1215
- #### 3. Efficient Prompt Design
1216
- ```javascript
1217
- // Good: Clear, specific prompts
1218
- .setPrompt(`
1219
- You are a customer service agent. Follow these steps:
1220
-
1221
- 1. Greet the customer politely
1222
- 2. Understand their issue by asking clarifying questions
1223
- 3. Provide a solution or escalate if needed
1224
- 4. Confirm resolution
1225
-
1226
- Response format: JSON with fields: greeting, questions, solution, status
1227
- `);
1228
- ```
1229
-
1230
- ### 🔄 Development Workflow
1231
-
1232
- #### 1. Local Development
1233
- ```bash
1234
- # 1. Start with development configuration
1235
- NODE_ENV=development dank run
1236
-
1237
- # 2. Make changes to dank.config.js
1238
-
1239
- # 3. Restart agents to apply changes
1240
- dank stop --all
1241
- dank run --build # Rebuild if needed
1242
-
1243
- # 4. Test with reduced resources
1244
- createAgent('dev-agent').setResources({ memory: '128m', cpu: 0.25 })
1245
- ```
1246
-
1247
- #### 2. Testing Agents
1248
- ```bash
1249
- # Test individual agents
1250
- dank run --detached
1251
- dank logs test-agent --follow
1252
-
1253
- # Check health endpoints
1254
- curl http://localhost:3001/health
1255
-
1256
- # Monitor resource usage
1257
- docker stats dank-test-agent
1258
- ```
1259
-
1260
- #### 3. Production Deployment
1261
- ```bash
1262
- # 1. Set production environment
1263
- export NODE_ENV=production
1264
-
1265
- # 2. Build optimized images
1266
- dank build --base --force
1267
-
1268
- # 3. Start with production config
1269
- dank run --detached
1270
-
1271
- # 4. Monitor and scale as needed
1272
- dank status --watch
1273
- ```
1274
-
1275
- ### Monitoring and Debugging
1276
-
1277
- ```bash
1278
- # Watch all agents in real-time
1279
- dank status --watch
1280
-
1281
- # Follow logs from specific agent
1282
- dank logs my-agent --follow
1283
-
1284
- # View container details
1285
- docker ps -f name=dank-
1286
-
1287
- # Check agent health
1288
- curl http://localhost:3001/health
1289
- ```
1290
-
1291
- ## 📦 Installation
1292
-
1293
- ### Prerequisites
1294
- - Node.js 16+
1295
- - Docker Desktop or Docker Engine
1296
- - npm or yarn
1297
-
1298
- ### Global Installation
1299
- ```bash
1300
- npm install -g dank-ai
1301
- ```
1302
-
1303
- ### Local Development
1304
- ```bash
1305
- git clone https://github.com/your-org/dank
1306
- cd dank
1307
- npm install
1308
- npm link # Creates global symlink
1309
- ```
1310
-
1311
- ## 🤝 Contributing
1312
90
 
1313
- 1. Fork the repository
1314
- 2. Create a feature branch: `git checkout -b feature/amazing-feature`
1315
- 3. Commit changes: `git commit -m 'Add amazing feature'`
1316
- 4. Push to branch: `git push origin feature/amazing-feature`
1317
- 5. Open a Pull Request
91
+ ## Configuration
1318
92
 
1319
- ## 📄 License
93
+ Edit `dank.config.js` to:
1320
94
 
1321
- ISC License - see LICENSE file for details.
95
+ - Define your agents and their capabilities
96
+ - Set up LLM providers and models
97
+ - Configure event handlers
98
+ - Set Docker and resource limits
99
+ - Enable/disable communication features
1322
100
 
1323
- ## 🆘 Support
101
+ ## Documentation
1324
102
 
1325
- - **Documentation**: [Wiki](https://github.com/your-org/dank/wiki)
1326
- - **Issues**: [GitHub Issues](https://github.com/your-org/dank/issues)
1327
- - **Discussions**: [GitHub Discussions](https://github.com/your-org/dank/discussions)
103
+ For more information, visit the [Dank Framework Documentation](https://github.com/your-org/dank).
1328
104
 
1329
- ---
105
+ ## License
1330
106
 
1331
- **Built with 💯 energy for the AI agent revolution!** 🚀
107
+ ISC