dudoxx-tool-factory
v1.0.0
Published
Comprehensive tool management system for AI-powered applications with DUDOXX provider integration
Maintainers
Readme
DUDOXX Tool Factory
A comprehensive tool management system for AI-powered applications, built on top of the AI SDK and DUDOXX provider. Provides enterprise-grade features including parallel execution, retry mechanisms, fallback strategies, session management, and comprehensive monitoring.
🚀 Features
Core Capabilities
- 🔧 Tool Registry: Centralized tool management with validation and metadata
- ⚡ Multiple Execution Strategies: Sequential, parallel, mixed, and priority-based execution
- 🔄 Smart Retry Logic: Configurable retry policies with exponential backoff
- 🛡️ Fallback Mechanisms: Graceful degradation and alternative tool execution
- 📱 Session Management: Stateful chat sessions with tool associations
- 📊 Performance Monitoring: Real-time metrics, logging, and health monitoring
- 🎯 AI SDK Integration: Seamless integration with Vercel AI SDK
- 🔗 DUDOXX Provider Support: Native support for DUDOXX LLM models
Advanced Features
- 🏃♂️ Parallel Tool Execution: Execute multiple tools concurrently with configurable limits
- 🔄 Multi-step Workflows: Tools with dependencies and complex execution flows
- 📈 Auto-scaling: Dynamic resource management based on load
- 🔍 Tool Discovery: Search and filter tools by category, tags, and capabilities
- ⚠️ Error Recovery: Comprehensive error handling with automatic retries
- 📝 Structured Logging: Multi-level logging with contextual information
- 🎛️ Configuration Management: Environment-specific configurations
📦 Installation
npm install dudoxx-tool-factory🏁 Quick Start
import { createDevToolFactory } from 'dudoxx-tool-factory';
// Create tool factory with DUDOXX provider
const factory = createDevToolFactory(
process.env.DUDOXX_API_KEY!,
process.env.DUDOXX_BASE_URL
);
// Generate AI response with tool support
const result = await factory.generate({
prompt: "Calculate 25 * 8 and tell me the current time",
model: 'dudoxx',
tools: {
calculator: factory.getTool('calculator')!,
'current-time': factory.getTool('current-time')!,
},
});
console.log(result.text);🔧 Tool Creation
Simple Tool
import { createSimpleTool, ToolCategories } from 'dudoxx-tool-factory';
import { z } from 'zod';
const greetingTool = createSimpleTool({
id: 'greeting',
name: 'Greeting Generator',
description: 'Generates personalized greetings',
category: ToolCategories.TEXT,
parameters: z.object({
name: z.string().describe('Name of the person to greet'),
style: z.enum(['formal', 'casual', 'friendly']),
}),
handler: async (input, context) => {
const greeting = `Hello ${input.name}! Nice to meet you.`;
context.logger.info(`Generated greeting for ${input.name}`);
return { greeting, timestamp: new Date() };
},
});
await factory.registerTool(greetingTool);Async Tool with Retry
import { createAsyncTool } from 'dudoxx-tool-factory';
const weatherTool = createAsyncTool({
id: 'weather-api',
name: 'Weather Service',
description: 'Fetches weather data from external API',
parameters: z.object({
location: z.string(),
units: z.enum(['metric', 'imperial']).optional(),
}),
handler: async (input, context) => {
const response = await fetch(`/api/weather?location=${input.location}`);
return await response.json();
},
timeout: 10000,
retryAttempts: 3,
parallelizable: true,
});🎯 Execution Strategies
Sequential Execution
const plan = factory.createExecutionPlan()
.addTool('step1', { data: 'input' })
.addTool('step2', { data: 'input' }, { dependencies: ['step1'] })
.addTool('step3', { data: 'input' }, { dependencies: ['step2'] })
.setStrategy('sequential')
.build();
const results = await factory.executeTools(plan);Parallel Execution
const plan = factory.createExecutionPlan()
.addTool('tool1', { input: 'data' })
.addTool('tool2', { input: 'data' })
.addTool('tool3', { input: 'data' })
.setStrategy('parallel')
.setConcurrency(3)
.build();
const results = await factory.executeTools(plan);Priority-based Execution
const plan = factory.createExecutionPlan()
.addTool('critical', { data: 'input' }, { priority: 10 })
.addTool('normal', { data: 'input' }, { priority: 5 })
.addTool('background', { data: 'input' }, { priority: 1 })
.setStrategy('priority')
.build();
const results = await factory.executeTools(plan);📱 Session Management
// Create a chat session
const session = await factory.createSession({
userId: 'user-123',
model: 'dudoxx',
tools: ['calculator', 'weather', 'current-time'],
metadata: { context: 'customer-support' },
});
// Use session in chat
const chatResult = await factory.chat({
sessionId: session.id,
messages: [
{ role: 'user', content: 'What\'s the weather like and what time is it?' }
],
tools: {
weather: factory.getTool('weather')!,
'current-time': factory.getTool('current-time')!,
},
});
// Update session with more tools
await factory.updateSession(session.id, {
tools: ['calculator', 'weather', 'current-time', 'text-analysis'],
});📊 Monitoring and Analytics
Performance Dashboard
const dashboard = factory.getDashboard();
console.log('Performance Overview:', dashboard.overview);
console.log('Top Metrics:', dashboard.topMetrics);
console.log('System Health:', dashboard.performance);Health Monitoring
const health = factory.getHealth();
console.log(`System Status: ${health.status}`);
console.log('Component Health:', health.components);
if (health.status === 'warning') {
console.log('Issues:', health.issues);
}Metrics Export
// Export as JSON
const jsonMetrics = factory.exportMetrics('json');
// Export as Prometheus format
const prometheusMetrics = factory.exportMetrics('prometheus');🔄 Streaming with Tools
const { stream, sessionId } = await factory.stream({
messages: [
{ role: 'user', content: 'Calculate some math and tell me a joke' }
],
model: 'dudoxx',
tools: {
calculator: factory.getTool('calculator')!,
joke: factory.getTool('joke-generator')!,
},
onChunk: (chunk) => process.stdout.write(chunk),
onToolResult: (result) => console.log('Tool used:', result.metadata.toolId),
onFinish: (finalText) => console.log('Stream complete'),
});
// Process stream
const reader = stream.getReader();
try {
while (true) {
const { done, value } = await reader.read();
if (done) break;
// Process chunk
}
} finally {
reader.releaseLock();
}⚙️ Configuration
Development Configuration
import { createDevelopmentConfig, createToolFactory } from 'dudoxx-tool-factory';
const config = createDevelopmentConfig({
provider: {
apiKey: process.env.DUDOXX_API_KEY!,
baseURL: process.env.DUDOXX_BASE_URL,
defaultModel: 'dudoxx',
},
monitoring: {
logLevel: 'debug',
enableMetrics: true,
},
});
const factory = createToolFactory(config);Production Configuration
import { createProductionConfig, createToolFactory } from 'dudoxx-tool-factory';
const config = createProductionConfig({
provider: {
apiKey: process.env.DUDOXX_API_KEY!,
baseURL: process.env.DUDOXX_BASE_URL,
},
execution: {
maxConcurrency: 20,
defaultTimeout: 10000,
},
monitoring: {
logLevel: 'warn',
enableEvents: false, // Reduce overhead
},
});
const factory = createToolFactory(config);🛠️ Built-in Tools
The factory comes with several built-in tools:
- Calculator: Mathematical calculations and expressions
- Current Time: Date and time in various formats and timezones
- Random Number: Cryptographically secure random number generation
- Text Analysis: Text metrics, word count, sentiment analysis
- Weather: Mock weather service (customizable)
// List all built-in tools
const tools = factory.listTools();
console.log('Available tools:', tools.map(t => t.id));
// Get specific tool
const calculator = factory.getTool('calculator');
if (calculator) {
console.log('Calculator description:', calculator.description);
}📋 Error Handling
Retry Policies
const toolWithRetry = createAsyncTool({
id: 'api-tool',
name: 'External API Tool',
description: 'Calls external API with retry logic',
parameters: z.object({ query: z.string() }),
handler: async (input) => {
// API call that might fail
const response = await fetch('/api/external');
return response.json();
},
retryAttempts: 3,
timeout: 5000,
});Fallback Strategies
const toolWithFallback = {
id: 'reliable-tool',
// ... other properties
execution: {
handler: primaryHandler,
fallbackStrategy: {
enabled: true,
fallbackTools: ['backup-tool'],
fallbackHandler: async (error, context) => {
context.logger.warn('Primary tool failed, using fallback');
return { fallback: true, message: 'Service temporarily unavailable' };
},
},
},
};🚦 Event System
// Listen to tool events
factory.on('tool.event', (event) => {
console.log(`Tool event: ${event.type}`, event.data);
});
// Listen to execution events
factory.on('execution.event', (event) => {
if (event.type === 'execution.failed') {
console.error('Execution failed:', event.data);
}
});
// Listen to session events
factory.on('session.event', (event) => {
console.log(`Session ${event.sessionId}: ${event.type}`);
});
// Listen to metrics events
factory.on('metrics.flush', (data) => {
console.log('Metrics updated:', data.dashboard.overview);
});🧪 Testing
# Run all tests
npm test
# Run tests in watch mode
npm run test:watch
# Run demo
npm run demo
# Run specific demo
npm run demo:simple
npm run demo:performance📖 API Reference
Core Classes
ToolFactory: Main orchestrator classToolRegistry: Tool management and discoverySessionManager: Chat session lifecycle managementToolExecutor: Tool execution engineLogger: Structured logging systemMetricsCollector: Performance monitoring
Utility Functions
createToolFactory(config): Create factory with custom configcreateDevToolFactory(apiKey, baseURL?): Quick development setupcreateProdToolFactory(options): Production-optimized setupcreateSimpleTool(options): Create basic toolcreateAsyncTool(options): Create async tool with retrytoolFromFunction(id, name, description, schema, fn): Convert function to tool
Configuration Helpers
createDefaultConfig(overrides?): Base configurationcreateDevelopmentConfig(overrides?): Development settingscreateProductionConfig(overrides?): Production settings
🤝 Contributing
- Fork the repository
- Create your feature branch (
git checkout -b feature/amazing-feature) - Commit your changes (
git commit -m 'Add some amazing feature') - Push to the branch (
git push origin feature/amazing-feature) - Open a Pull Request
📄 License
This project is licensed under the MIT License - see the LICENSE file for details.
🔗 Links
🆘 Support
For support and questions:
- Create an issue on GitHub
- Check existing documentation
- Review the demo files for examples
Built with ❤️ by the DUDOXX Team
