dead-wire-ai
v1.0.0
Published
A modular AI framework for building LLM-powered applications, agents, tool systems, and multi-model routing.
Downloads
24
Maintainers
Readme
🕸 Dead Wire AI Kit
A modular, lightweight AI framework for building LLM-powered applications, autonomous agents, tool systems, and multi-model routing — in Node.js.
Dead Wire AI Kit is a no-fluff alternative to LangChain. It's simpler, more modular, and easier to extend. Every system is independent — use what you need, ignore what you don't.
✨ Features
| System | Description | |---|---| | 🔧 Tool System | Register async tools with JSON schema validation, retries, and timeouts | | 🤖 Agent Loop | Autonomous multi-step reasoning with tool calling and memory | | 🧠 Memory | Short-term (session) + long-term (persistent JSON) with keyword retrieval | | 🔀 Model Router | Route between OpenAI, Anthropic, Ollama with fallback strategies | | 📝 Prompt Engine | Structured messages, output validation, retry logic, streaming sim | | ✅ Validation | JSON schema validation, hallucination detection, response sanitization | | ⚡ Cache | TTL-based prompt→response caching to avoid duplicate LLM calls | | 🐛 Debug | Full trace logging with console-based timeline viewer | | 🎣 Events | Lifecycle hooks: onPrompt, onResponse, onToolCall, onError, etc. | | 🔌 Plugins | Extend via memory, tool, model, and middleware plugins |
🚀 Quick Start
import DeadWireAI from 'dead-wire-ai';
const ai = new DeadWireAI({ debug: true });
// Register a tool
ai.registerTool({
name: 'getWeather',
description: 'Gets weather for a city',
schema: { city: 'string' },
run: async ({ city }) => ({ temp: 72, condition: 'Sunny' }),
});
// Simple question
const result = await ai.ask('What is the capital of Japan?');
console.log(result.answer);
// Autonomous agent with tool use
const agent = ai.createAgent({ name: 'MyAgent', maxSteps: 8 });
const agentResult = await agent.run('What is the weather in Tokyo?');
console.log(agentResult.answer);📦 Installation
# Clone or copy the project
cd dead-wire-ai
npm install # no external dependencies needed for core🏗 Architecture
dead-wire-ai/
src/
core/ DeadWireAI.js — Main API class
PromptEngine.js — Message builder, tool parser, validation
agent/ Agent.js — Autonomous agent loop
tools/ ToolRegistry.js — Tool registration + execution
memory/ MemoryManager.js — Short + long-term memory
models/ adapters.js — OpenAI, Anthropic, Ollama, Mock
ModelRouter.js — Multi-model routing + fallback
cache/ CacheSystem.js — TTL-based response cache
validation/ OutputValidator.js — Schema validation, JSON extraction
debug/ DebugLogger.js — Trace logger + timeline viewer
events/ EventBus.js — Lifecycle event hooks
plugins/ PluginSystem.js — Plugin + middleware system
index.js — Public API exports
bin/deadwire.js — CLI tool
examples/ — Example scripts
memory/ — Persistent memory storage (auto-created)🔧 Tool System
ai.registerTool({
name: 'searchWeb',
description: 'Searches the web for information',
schema: {
query: { type: 'string', description: 'Search query' },
limit: { type: 'number', optional: true },
},
run: async ({ query, limit = 5 }) => {
// your async logic
return { results: [...] };
},
options: {
timeout: 10000, // ms
maxRetries: 2,
},
});
// Direct tool execution
const result = await ai.executeTool('searchWeb', { query: 'Node.js ESM' });
// List all tools
console.log(ai.listTools());🤖 Agent System
const agent = ai.createAgent({
name: 'ResearchBot',
maxSteps: 10,
systemPrompt: 'You are a research assistant. Be thorough.',
});
const result = await agent.run('Research the top 5 JavaScript frameworks in 2025');
console.log(result.answer); // Final answer
console.log(result.steps); // All reasoning steps
console.log(result.totalSteps); // How many iterations
console.log(result.toolsUsed); // How many tool calls were made
console.log(result.duration_ms); // Total time🧠 Memory System
// Long-term persistent memory
ai.addMemory('user_name', 'Alice');
ai.addMemory('project', 'Building a weather app');
// Retrieve specific
const mem = ai.getMemory('user_name');
// Keyword search
const related = ai.searchMemory('weather app', 5);
// Delete
ai.deleteMemory('old_key');
// Stats
console.log(ai.memoryStats()); // { shortTerm: 12, longTerm: 5 }🔀 Model Router
import { OpenAIAdapter, AnthropicAdapter, OllamaAdapter } from 'dead-wire-ai';
// Register models
ai.registerModel('openai', new OpenAIAdapter({ apiKey: process.env.OPENAI_API_KEY }), true);
ai.registerModel('anthropic', new AnthropicAdapter());
ai.registerModel('ollama', new OllamaAdapter({ model: 'llama3.2' }));
// Set routing strategy
ai.setRoutingStrategy('fastest'); // 'default' | 'fastest' | 'cheapest' | 'best'
// Fallback chain
ai.setFallbackChain(['openai', 'anthropic', 'ollama', 'mock']);
// Override per-call
const result = await ai.ask('Hello', { model: 'ollama' });
// Stats
console.log(ai.modelStats());✅ Output Validation
// Enforce JSON output with schema
const result = await ai.ask('List 3 cities as JSON', {
schema: {
type: 'object',
required: ['cities'],
properties: {
cities: { type: 'array', items: { type: 'string' } },
},
},
});
console.log(result.parsed); // Already-parsed JSON
console.log(result.validation); // { valid, errors, warnings }⚡ Cache System
// Cache is on by default (5 min TTL)
const r1 = await ai.ask('What is 2 + 2?'); // calls model
const r2 = await ai.ask('What is 2 + 2?'); // returns from cache
console.log(r2.cached); // true
console.log(ai.cacheStats()); // { size, hits, misses, hitRate }
// Disable cache for a call
const fresh = await ai.ask('Latest news?', { useCache: false });
// Clear all
ai.clearCache();🎣 Event System
ai.onPrompt(({ messages }) => {
console.log('Sending prompt...');
});
ai.onResponse(({ content }) => {
console.log('Got response:', content.slice(0, 50));
});
ai.onToolCall(({ tool, args }) => {
console.log(`Tool called: ${tool}`);
});
ai.onToolResult(({ tool, result }) => {
console.log(`Tool result from ${tool}:`, result);
});
ai.onError(({ source, error }) => {
console.error(`Error in ${source}:`, error.message);
});
ai.onAgentStep(({ step }) => {
console.log(`Agent step ${step}`);
});
ai.onAgentDone(({ answer, totalSteps }) => {
console.log(`Done in ${totalSteps} steps`);
});🔌 Plugin System
import { createTokenCounterPlugin, createAutoMemoryPlugin } from 'dead-wire-ai';
// Built-in plugins
ai.usePlugin(createTokenCounterPlugin());
ai.usePlugin(createAutoMemoryPlugin({ minLength: 150 }));
// Check token usage (added by token-counter plugin)
console.log(ai.tokenUsage()); // { input, output, calls }
// Custom plugin
ai.usePlugin({
name: 'my-logger',
version: '1.0.0',
tools: [
// auto-register additional tools
{ name: 'ping', description: 'Ping check', schema: {}, run: async () => 'pong' }
],
middleware: {
beforePrompt: (ctx) => {
console.log('[MyPlugin] Before prompt');
return ctx; // return modified context
},
afterResponse: (ctx) => {
console.log('[MyPlugin] Got response');
return ctx;
},
},
install(ai) {
// Called once when plugin is installed
ai.myPluginData = { installed: true };
},
});🐛 Debug System
// Enable debug
ai.enableDebug(true); // true = verbose (shows full messages)
// Each call now logs:
// 📤 PROMPT → model: [user] What is...
// 🤖 MODEL Selected: mock (32ms)
// 📥 RESPONSE ← "Here is the answer..." | tokens: ~45
// 🔧 TOOL CALL → getWeather({"city":"Tokyo"})
// ✅ TOOL RES ← getWeather: {"temp":82,...} (12ms)
// 🏁 DONE Completed in 2 step(s)
// Print full timeline at end
ai.printTimeline();💻 CLI
# Install globally (after npm link or npm install -g)
deadwire run "What is the capital of France?"
deadwire run "Explain black holes" --debug
deadwire run "What's the weather?" --model ollama --stream
# Agent mode
deadwire agent "Research top 5 JS frameworks"
deadwire agent "Plan a 3-day Tokyo itinerary" --max-steps 12
# Memory management
deadwire memory list
deadwire memory add "my_city" "Denver"
deadwire memory search "programming"
deadwire memory delete "my_city"
# System info
deadwire tools
deadwire status🌍 Environment Variables
OPENAI_API_KEY=sk-...
ANTHROPIC_API_KEY=sk-ant-...Without API keys, the framework uses the built-in Mock adapter — fully functional for testing and development.
🧩 Examples
node examples/basic-agent.js # Core API demo
node examples/weather-agent.js # Multi-tool agent
node examples/multi-model.js # Model routing demo📄 License
MIT — use freely, build anything.
