Package Exports
- @agentdao/core
- @agentdao/core/dist/index.js
This package does not declare an exports field, so the exports above have been automatically detected and optimized by JSPM instead. If any package subpath is missing, it is recommended to post an issue to the original package (@agentdao/core) to support the "exports" field. If that is not possible, create a JSPM override to customize the exports field for this package.
Readme
@agentdao/core
Core functionality and skills for AgentDAO - Web3 subscriptions, content generation, social media, help support, live chat, RSS fetching, and web search.
๐ What's New in v0.4.3
โจ Major Improvements
- ๐ Analytics Service: Built-in analytics tracking for all skills and agents
- ๐ง FundAgent Enhanced: Completely robust with rate limiting, retry logic, and intelligent fallback mechanisms
- ๐ค ContentGeneratorSkill: Enhanced with comprehensive error handling, validation, and retry mechanisms
- โก Production Ready: 9/10 skills now production-ready with real implementations
- ๐งช Comprehensive Testing: 33 tests passing with full coverage
- ๐ก๏ธ Error Handling: Improved error handling across all skills with graceful fallbacks
- ๐ Rate Limiting: Smart rate limiting for blockchain and API calls
- ๐ Test Address Detection: Automatic detection and handling of test environments
๐ฏ Production Status
| Skill | Status | Features |
|---|---|---|
| AnalyticsService | โ Production Ready | Built-in analytics tracking, performance monitoring |
| ContentGeneratorSkill | โ Production Ready | AI content generation, SEO optimization, error handling |
| FundAgent | โ Production Ready | Safe wallet management, rate limiting, fallbacks |
| WebSearchSkill | โ Production Ready | AI-powered web search with analysis, analytics tracking |
| SocialMediaSkill | โ Production Ready | Multi-platform posting and analytics |
| HelpSupportSkill | โ Production Ready | AI customer support automation |
| Web3SubscriptionSkill | โ Production Ready | ADAO token subscriptions on Base |
| TokenGatingSkill | โ Production Ready | Token-gated access control |
| TokenGatingService | โ Production Ready | Access management service |
| LiveChatSkill | โ Production Ready | Real-time chat with AI assistance |
| PhotoSkill | โ ๏ธ Requires API Key | Unsplash photo integration |
๐ Key Features Added
- Rate Limiting: Configurable rate limiting (30 requests/minute default)
- Retry Logic: Exponential backoff with smart error detection
- Fallback Mechanisms: Graceful degradation when services are unavailable
- Test Environment Support: Mock responses for development and testing
- Enhanced Error Logging: Comprehensive error tracking and reporting
- TypeScript Support: Full type definitions and IntelliSense support
๐ Quick Start
1. Install the Package
npm install @agentdao/core
# or
yarn add @agentdao/core
# or
pnpm add @agentdao/core2. Configure API Keys
Add your API keys to your .env file in your app's root directory:
# Required for AI features (WebSearchSkill, ContentGeneratorSkill, etc.)
OPENAI_API_KEY=sk-your-openai-api-key-here
# Optional: For enhanced WebSearchSkill (Google Search API)
GOOGLE_SEARCH_API_KEY=your-google-search-api-key
GOOGLE_SEARCH_ENGINE_ID=your-google-search-engine-id
# Optional: For enhanced WebSearchSkill (Bing Search API)
BING_SEARCH_API_KEY=your-bing-search-api-key
# Required: For OpenAI web search fallback (used when Google/Bing fail)
OPENAI_API_KEY=sk-your-openai-api-key-here
# Optional: For news search (NewsAPI)
NEWS_API_KEY=your-news-api-key
# Required for SocialMediaSkill
TWITTER_API_KEY=your-twitter-api-key
TWITTER_API_SECRET=your-twitter-api-secret
TWITTER_ACCESS_TOKEN=your-twitter-access-token
TWITTER_ACCESS_TOKEN_SECRET=your-twitter-access-token-secret
# Required for PhotoSkill
UNSPLASH_ACCESS_KEY=your-unsplash-access-key
# Optional: For blockchain interactions
ETHEREUM_RPC_URL=https://mainnet.infura.io/v3/YOUR_INFURA_KEY
POLYGON_RPC_URL=https://polygon-rpc.com
ARBITRUM_RPC_URL=https://arb1.arbitrum.io/rpc
# Optional: For persistent storage
DATABASE_URL=postgresql://username:password@localhost:5432/agentdao
DATABASE_API_KEY=your-database-api-key3. Use the Skills
import { ContentGeneratorSkill, validateSkillConfig } from '@agentdao/core';
// Check if skill is properly configured
const validation = validateSkillConfig('ContentGeneratorSkill');
if (!validation.valid) {
console.log(validation.instructions);
process.exit(1);
}
// Create skill instance (will automatically use API keys from .env)
const skill = new ContentGeneratorSkill({
agentId: 'my-agent',
agentName: 'My Agent',
domain: 'myapp.com',
ai: {
provider: 'openai',
model: 'gpt-4'
// apiKey will be automatically loaded from OPENAI_API_KEY
}
});
// Generate content
const blogPost = await skill.generateBlogPost('AI', ['artificial intelligence']);
console.log(blogPost);๐ง Configuration Validation
The package automatically validates your configuration and provides helpful warnings if API keys are missing:
import { validateSkillConfig, getSetupInstructions } from '@agentdao/core';
// Check configuration for any skill
const validation = validateSkillConfig('SocialMediaSkill');
if (!validation.valid) {
console.log(validation.instructions);
// This will show you exactly what to add to your .env file
}๐ Available Skills
๐ Analytics Service
- AnalyticsService: Built-in analytics tracking for all skills and agents
- Automatic tracking of skill usage, API calls, errors, and performance
- Rate limiting and batch processing to prevent performance impact
- Integration with AgentDAO platform for centralized analytics
- Custom event tracking with metadata support
- Performance monitoring and error tracking
๐ค AI-Powered Skills
- WebSearchSkill: Intelligent web search with AI-powered result analysis
- Supports Google Search API, Bing Search API, and OpenAI web search (fallback)
- News search via NewsAPI
- Image search via Unsplash
- AI-powered result analysis and recommendations
- Automatic fallback to OpenAI web search when other providers fail
- NEW: Built-in analytics tracking for search queries and performance
- ContentGeneratorSkill: Generate blog posts, social media content, emails, and more
- HelpSupportSkill: AI-powered customer support and help desk automation
- LiveChatSkill: Real-time chat support with AI assistance
๐ฑ Social Media Skills
- SocialMediaSkill: Post to Twitter, LinkedIn, and other platforms
- PhotoSkill: Search and manage photos from Unsplash, Pexels, and Pixabay
๐ Web3 Skills
- Web3SubscriptionSkill: Manage Web3 subscriptions and payments
- FundAgent: Interact with Safe wallets and manage funds (now with rate limiting & fallbacks)
- TokenGatingSkill: Implement token-gated access control
๐ง Utility Skills
- RssFetcherSkill: Fetch and parse RSS feeds
- ImageGenerationSkill: Generate images using AI models
๐ Analytics Service
The package now includes a built-in analytics service that automatically tracks important events across all skills.
Quick Start with Analytics
import { AnalyticsService, trackSkillUsage, trackApiCall, trackError } from '@agentdao/core';
// Initialize analytics (optional - enabled by default)
const analytics = AnalyticsService.getInstance({
enabled: true,
apiKey: process.env.AGENTDAO_API_KEY // Optional: for platform integration
});
// Track skill usage automatically
await trackSkillUsage('WebSearchSkill', 'my-agent-123', {
query: 'AI trends 2024',
provider: 'google'
});
// Track API calls
await trackApiCall('web_search', true, 1500, {
skill: 'WebSearchSkill',
resultCount: 10
});
// Track errors
await trackError(new Error('API timeout'), 'WebSearchSkill.searchWeb', 'my-agent-123');Analytics Features
- ๐ Automatic Tracking: Skills automatically track usage, errors, and performance
- ๐ฆ Batch Processing: Events are batched and sent efficiently
- โก Performance Optimized: Non-blocking, rate-limited tracking
- ๐ Platform Integration: Sends data to AgentDAO platform for centralized analytics
- ๐ก๏ธ Privacy Friendly: Only tracks important events, not every interaction
- ๐ Custom Events: Track custom events with rich metadata
Analytics Configuration
const analyticsConfig = {
enabled: true, // Enable/disable analytics
endpoint: 'https://your-analytics-endpoint.com', // Custom endpoint
apiKey: 'your-api-key', // For AgentDAO platform integration
batchSize: 10, // Events per batch
flushInterval: 30000, // Flush interval in ms
rateLimit: 10 // Events per minute per user
};
const analytics = AnalyticsService.getInstance(analyticsConfig);Available Analytics Functions
// Track skill usage
await trackSkillUsage(skillName, agentId, metadata);
// Track API calls
await trackApiCall(endpoint, success, duration, metadata);
// Track errors
await trackError(error, context, agentId, metadata);
// Track performance metrics
await trackPerformance(metric, value, unit, metadata);
// Track monetization events
await trackMonetization(event, amount, currency, metadata);
// Track custom events
await trackEvent({
event_type: 'custom',
event_name: 'user_action',
metadata: { action: 'button_click' }
});๐ API Key Requirements
| Skill | Required API Keys | Optional |
|---|---|---|
| WebSearchSkill | OPENAI_API_KEY |
GOOGLE_SEARCH_API_KEY, GOOGLE_SEARCH_ENGINE_ID, BING_SEARCH_API_KEY, NEWS_API_KEY |
| ContentGeneratorSkill | OPENAI_API_KEY |
- |
| SocialMediaSkill | TWITTER_API_KEY, TWITTER_API_SECRET, TWITTER_ACCESS_TOKEN, TWITTER_ACCESS_TOKEN_SECRET |
- |
| PhotoSkill | UNSPLASH_ACCESS_KEY |
- |
| HelpSupportSkill | OPENAI_API_KEY |
- |
| LiveChatSkill | OPENAI_API_KEY |
- |
| Web3SubscriptionSkill | - | ETHEREUM_RPC_URL, POLYGON_RPC_URL, ARBITRUM_RPC_URL |
| FundAgent | - | ETHEREUM_RPC_URL, POLYGON_RPC_URL, ARBITRUM_RPC_URL |
| TokenGatingSkill | - | ETHEREUM_RPC_URL, POLYGON_RPC_URL, ARBITRUM_RPC_URL |
๐ฏ Demo Mode
For testing without setting up all API keys, enable demo mode:
DEMO_MODE=trueThis allows skills to work with mock data for development and testing.
๐ก๏ธ Error Handling & Reliability
The package now includes robust error handling and reliability features:
Rate Limiting
// Configurable rate limiting for API calls
const config = {
rateLimit: {
maxRequestsPerMinute: 30,
retryAttempts: 3,
retryDelayMs: 1000
}
};Retry Logic
// Automatic retry with exponential backoff
// Smart error detection to avoid retrying non-retryable errorsFallback Mechanisms
// Graceful degradation when services are unavailable
// Mock responses for test environments
// Database fallbacks for persistent storage๐ Detailed Documentation
For detailed setup instructions and troubleshooting, see the Setup Guide.
Core Features
- Type-safe agent creation and execution
- Input and output validation
- Error handling with standardized error types
- Metadata tracking
- Extensible architecture
- NEW: Rate limiting and retry mechanisms
- NEW: Comprehensive error handling
- NEW: Test environment support
Skills Overview
This package includes powerful, composable skills that can be integrated into any application:
- Web3SubscriptionSkill - ADAO token-based subscription management on Base chain
- ContentGeneratorSkill - AI-powered content generation and optimization (enhanced with error handling)
- SocialMediaSkill - Multi-platform social media management and analytics
- HelpSupportSkill - AI customer support with knowledge base and ticket management
- LiveChatSkill - Real-time chat with moderation and file sharing
- RssFetcherSkill - RSS feed fetching and filtering with multi-feed aggregation
- WebSearchSkill - AI-powered web search with intelligent analysis and recommendations
- FundAgent - Safe wallet management with rate limiting and fallback mechanisms
- TokenGatingSkill - Token-gated access control for Web3 applications
- TokenGatingService - Access management service for token-gated features
Web3SubscriptionSkill
Manage subscriptions using ADAO tokens on Base chain with flexible billing periods. Now with enhanced multi-chain, multi-token support, advanced analytics, and subscription management.
๐ Enhanced Features (v2.0)
- ๐ Multi-Chain Support: Base, Polygon, Ethereum, and more
- ๐ฐ Multi-Token Payments: ADAO, USDC, ETH, MATIC, and custom tokens
- ๐ Advanced Analytics: Real-time metrics, churn analysis, lifetime value
- ๐ Subscription Management: Upgrades, downgrades, proration
- ๐ธ Refund Processing: Automated refunds with approval workflows
- ๐ Real-Time Webhooks: Instant notifications for all events
- ๐ Reduced Platform Fee: Now 10% (down from 15%)
- ๐ก๏ธ Enhanced Security: Fraud detection, rate limiting, signature verification
Web3SubscriptionSkill Setup
import { Web3SubscriptionSkill } from '@agentdao/core';
import { EnhancedWeb3SubscriptionSkill } from '@agentdao/core'; // Enhanced versionBasic Configuration (Backward Compatible)
const subscriptionConfig = {
agentId: 'my-agent-123',
agentName: 'My Agent',
domain: 'myagent.agentdao.com',
// ADAO Token Configuration (Base chain)
adaoToken: {
address: '0x...', // ADAO contract address on Base
decimals: 18,
network: 'base',
logo: 'https://example.com/adao-logo.png'
},
// Subscription Plans
plans: {
basic: {
name: 'Basic Plan',
description: 'Essential features',
features: ['chat', 'basic_analytics'],
pricing: {
monthly: { price: 100, discount: 0 },
quarterly: { price: 270, discount: 10 },
annually: { price: 960, discount: 20 }
}
},
pro: {
name: 'Pro Plan',
description: 'Advanced features',
features: ['chat', 'analytics', 'priority_support'],
pricing: {
monthly: { price: 250, discount: 0 },
quarterly: { price: 675, discount: 10 },
annually: { price: 2400, discount: 20 }
}
}
},
// Provider Configuration
provider: {
rpcUrl: 'https://mainnet.base.org',
chainId: 8453
}
};Enhanced Configuration (New Features)
const enhancedConfig = {
// Original config
...subscriptionConfig,
// Multi-chain support
chains: {
8453: { // Base
name: 'Base',
rpcUrl: 'https://mainnet.base.org',
explorer: 'https://basescan.org',
nativeToken: 'ETH'
},
137: { // Polygon
name: 'Polygon',
rpcUrl: 'https://polygon-rpc.com',
explorer: 'https://polygonscan.com',
nativeToken: 'MATIC'
}
},
// Multi-token support
tokens: {
'0x...': { // ADAO on Base
name: 'ADAO Token',
symbol: 'ADAO',
decimals: 18,
chainId: 8453
},
'0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913': { // USDC on Base
name: 'USD Coin',
symbol: 'USDC',
decimals: 6,
chainId: 8453
}
},
// Webhook system
webhooks: {
subscriptionCreated: 'https://myapp.com/webhooks/subscription-created',
paymentProcessed: 'https://myapp.com/webhooks/payment-processed',
refundIssued: 'https://myapp.com/webhooks/refund-issued'
},
// Refund system
refunds: {
enabled: true,
gracePeriod: 7, // days
autoRefund: true,
refundPolicy: 'prorated',
requireApproval: false
},
// Subscription management
subscriptionManagement: {
allowUpgrades: true,
allowDowngrades: true,
prorationEnabled: true,
trialPeriod: 7,
gracePeriod: 3,
autoRenewal: true
},
// Platform fee (10%)
platformFee: {
percentage: 10,
safeAddress: '0x...',
autoTransfer: true
}
};Basic Usage (Backward Compatible)
const subscriptionSkill = new Web3SubscriptionSkill(subscriptionConfig);
// Create a subscription
const subscription = await subscriptionSkill.createSubscription(
'0x1234...', // user address
'pro', // plan ID
'monthly' // billing period
);
// Check subscription status
const status = await subscriptionSkill.checkSubscription(
'0x1234...' // user address
);
// Get revenue analytics
const analytics = await subscriptionSkill.getRevenueStats();Enhanced Usage (New Features)
const enhancedSkill = new EnhancedWeb3SubscriptionSkill(enhancedConfig);
// Get available payment methods across chains
const paymentMethods = await enhancedSkill.getPaymentMethods(userAddress);
// Create enhanced subscription with analytics
const enhancedSubscription = await enhancedSkill.createEnhancedSubscription(
userAddress,
planId,
billingPeriod,
paymentMethod
);
// Subscription upgrades with proration
const upgradedSubscription = await enhancedSkill.upgradeSubscription(
userAddress,
'pro',
'monthly'
);
// Subscription downgrades with credits
const downgradedSubscription = await enhancedSkill.downgradeSubscription(
userAddress,
'basic',
'monthly'
);
// Process refunds
const refundRecord = await enhancedSkill.processRefund(
userAddress,
100,
'Customer request'
);
// Get enhanced analytics
const analytics = await enhancedSkill.getEnhancedAnalytics(userAddress);
const revenueStats = await enhancedSkill.getEnhancedRevenueStats();Web3SubscriptionSkill Key Features
- โ ADAO token payments on Base chain
- โ Monthly, quarterly, and annual billing
- โ Automatic subscription management
- โ Revenue tracking and analytics
- โ Plan upgrades and downgrades
- โ Subscription cancellation
- โ Multi-chain support (Base, Polygon, Ethereum)
- โ Multi-token payments (ADAO, USDC, ETH, MATIC)
- โ Advanced analytics and insights
- โ Real-time webhooks
- โ Automated refund processing
- โ 10% platform fee (reduced from 15%)
ContentGeneratorSkill
Generate AI-powered content for blogs, social media, emails, and more with SEO optimization. Now with enhanced error handling, validation, and retry mechanisms.
๐ ContentGeneratorSkill v0.4.2 Improvements
- ๐ก๏ธ Comprehensive Error Handling: Graceful handling of AI service failures
- ๐ Retry Logic: Automatic retry with exponential backoff for transient errors
- โ Input Validation: Robust validation of prompts and configuration
- ๐ Content Cleaning: Automatic cleaning and formatting of generated content
- ๐ ๏ธ Fallback Mechanisms: Fallback content generation when primary methods fail
- ๐ Error Logging: Detailed error tracking and reporting
- ๐ฏ Smart Parsing: Intelligent JSON parsing with fallback mechanisms
ContentGeneratorSkill Setup
import { ContentGeneratorSkill } from '@agentdao/core';ContentGeneratorSkill Configuration
const contentConfig = {
agentId: 'my-content-agent',
agentName: 'My Content Agent',
domain: 'myapp.com',
// AI Configuration with retry logic
ai: {
provider: 'openai',
apiKey: process.env.OPENAI_API_KEY,
model: 'gpt-4',
temperature: 0.7,
maxTokens: 2000,
retryAttempts: 3 // Enhanced retry configuration
},
// Brand Configuration
brand: {
name: 'My Company',
voice: 'Professional',
tone: 'Informative',
keywords: ['technology', 'innovation', 'solutions'],
styleGuide: 'Professional and informative tone'
},
// SEO Configuration
seo: {
enabled: true,
keywords: ['seo', 'marketing', 'digital'],
metaDescriptionLength: 160,
titleMaxLength: 60,
autoOptimize: true
},
// Content Templates with validation
templates: {
'blog-post': {
name: 'Blog Post',
type: 'blog',
prompt: 'Write a blog post about {{topic}}',
maxLength: 2000,
format: 'markdown',
variables: ['topic'],
examples: ['Example blog post about AI.']
},
'social-post': {
name: 'Social Media Post',
type: 'social',
prompt: 'Create a {{platform}} post about {{topic}}',
maxLength: 280,
format: 'text',
variables: ['platform', 'topic'],
examples: ['Example social media post.']
}
},
// Integration Configuration
integration: {
autoSave: true,
saveLocation: 'database',
publishAutomatically: false,
reviewRequired: false
},
// Categories for content organization
categories: ['technology', 'business', 'marketing']
};ContentGeneratorSkill Usage
const contentSkill = new ContentGeneratorSkill(contentConfig);
// Generate blog post
const blogPost = await contentSkill.generateBlogPost(
'AI in Healthcare',
['artificial intelligence', 'healthcare', 'innovation']
);
// Generate social media post
const socialPost = await contentSkill.generateSocialPost(
'twitter',
'New product launch'
);
// Optimize content for SEO
const optimized = await contentSkill.optimizeForSEO(
'Your content here...',
['keyword1', 'keyword2']
);
// Generate meta tags
const metaTags = await contentSkill.generateMetaTags(
'Page Title',
'Page description'
);ContentGeneratorSkill Key Features
- โ AI-powered content generation with retry logic
- โ Multi-platform social media posts with validation
- โ SEO optimization and scoring with auto-optimization
- โ Content templates and variables with type safety
- โ Brand voice customization with style guides
- โ Meta tag generation with length optimization
- โ Error handling and recovery with graceful fallbacks
- โ Input validation with comprehensive checks
- โ Content cleaning with automatic formatting
- โ Smart parsing with JSON fallback mechanisms
SocialMediaSkill
Manage social media presence across multiple platforms with scheduling and analytics.
SocialMediaSkill Setup
import { SocialMediaSkill } from '@agentdao/core';SocialMediaSkill Configuration
const socialConfig = {
platforms: {
twitter: {
enabled: true,
accessToken: process.env.TWITTER_ACCESS_TOKEN,
username: '@mycompany'
},
linkedin: {
enabled: true,
accessToken: process.env.LINKEDIN_ACCESS_TOKEN,
companyId: '123456'
},
facebook: {
enabled: true,
accessToken: process.env.FACEBOOK_ACCESS_TOKEN,
pageId: '987654321'
},
instagram: {
enabled: true,
accessToken: process.env.INSTAGRAM_ACCESS_TOKEN,
accountId: 'insta123'
}
},
scheduling: {
enabled: true,
timezone: 'UTC',
defaultTime: '09:00'
},
analytics: {
enabled: true,
trackEngagement: true,
trackReach: true
}
};SocialMediaSkill Usage
const socialSkill = new SocialMediaSkill(socialConfig);
// Post to all platforms
const results = await socialSkill.postToAll(
'Exciting news! We just launched our new feature.',
[{ type: 'image', url: 'https://example.com/image.jpg' }]
);
// Post to specific platform
const result = await socialSkill.postToPlatform(
'twitter',
'Check out our latest blog post!',
[]
);
// Schedule a post
const scheduled = await socialSkill.schedulePost(
'twitter',
'Scheduled post content',
new Date('2024-01-15T10:00:00Z')
);
// Get analytics
const analytics = await socialSkill.getPostAnalytics('post_id_123');SocialMediaSkill Key Features
- โ Multi-platform posting (Twitter, LinkedIn, Facebook, Instagram)
- โ Post scheduling and drafts
- โ Analytics and engagement tracking
- โ Comment management
- โ Mention monitoring
- โ File/media uploads
HelpSupportSkill
Provide AI-powered customer support with knowledge base and ticket management.
HelpSupportSkill Setup
import { HelpSupportSkill } from '@agentdao/core';HelpSupportSkill Configuration
const supportConfig = {
agentName: 'Customer Support Bot',
ai: {
provider: 'openai',
model: 'gpt-4',
apiKey: process.env.OPENAI_API_KEY,
maxTokens: 1000,
temperature: 0.7
},
escalationThreshold: 5, // messages before human escalation
humanSupport: {
enabled: true,
email: 'support@company.com',
phone: '+1-555-0123',
responseTime: '2 hours'
},
knowledgeBase: {
sources: [
'https://docs.company.com',
'https://help.company.com'
],
autoUpdate: true
}
};HelpSupportSkill Usage
const supportSkill = new HelpSupportSkill(supportConfig);
// Handle customer message
const response = await supportSkill.handleMessage(
'How do I reset my password?',
{
userId: 'user123',
subscription: 'pro',
previousTickets: 2
}
);
// Start conversation
const conversationId = await supportSkill.startConversation('user123');
// Search knowledge base
const results = await supportSkill.searchKnowledgeBase('password reset');
// Create support ticket
const ticket = await supportSkill.createTicket(
'user123',
'Payment processing error',
'high'
);
// Get support analytics
const analytics = await supportSkill.getSupportAnalytics();HelpSupportSkill Key Features
- โ AI-powered responses with confidence scoring
- โ Automatic escalation to human support
- โ Knowledge base integration
- โ Support ticket management
- โ Conversation history tracking
- โ Analytics and common issue detection
LiveChatSkill
Real-time chat functionality with moderation, file sharing, and user management.
LiveChatSkill Setup
import { LiveChatSkill } from '@agentdao/core';LiveChatSkill Configuration
const chatConfig = {
maxParticipants: 50,
messageHistoryLimit: 100,
moderation: {
enabled: true,
profanityFilter: true,
spamDetection: true,
autoBlock: false,
filters: ['spam', 'inappropriate']
},
fileSharing: {
enabled: true,
maxFileSize: 10 * 1024 * 1024, // 10MB
allowedTypes: ['image/*', 'application/pdf']
},
notifications: {
enabled: true,
sound: true,
desktop: true
}
};LiveChatSkill Usage
const chatSkill = new LiveChatSkill(chatConfig);
// Start a chat
const chatId = await chatSkill.startChat('user123', {
userAgent: 'Mozilla/5.0...',
referrer: 'https://example.com'
});
// Send a message
const message = await chatSkill.sendMessage(
chatId,
'Hello everyone!',
'user123'
);
// Join/leave chat
await chatSkill.joinChat(chatId, 'user456');
await chatSkill.leaveChat(chatId, 'user456');
// Upload file
const fileMessage = await chatSkill.uploadFile(
chatId,
fileObject,
'user123'
);
// Get online users
const onlineUsers = await chatSkill.getOnlineUsers(chatId);
// Moderate message
const moderation = await chatSkill.moderateMessage('inappropriate content');
// Get chat analytics
const analytics = await chatSkill.getChatAnalytics(chatId);LiveChatSkill Key Features
- โ Real-time messaging
- โ File upload and sharing
- โ Message moderation and filtering
- โ User presence tracking
- โ Chat analytics
- โ Multi-user conversations
RssFetcherSkill
Fetch and filter RSS feeds with keyword filtering, date filtering, and multi-feed aggregation.
RssFetcherSkill Setup
import { RssFetcherSkill } from '@agentdao/core';RssFetcherSkill Configuration
const rssConfig = {
// Basic configuration (optional)
maxResults: 10,
timeout: 30000, // 30 seconds
retryAttempts: 3
};RssFetcherSkill Usage
const rssSkill = new RssFetcherSkill(rssConfig);
// Fetch a single RSS feed
const items = await rssSkill.fetchFeed('https://hnrss.org/frontpage', {
keyword: 'AI',
limit: 5,
after: '2024-01-01T00:00:00Z'
});
// Fetch multiple feeds
const multiFeedItems = await rssSkill.fetchFeed('', {
urls: [
'https://hnrss.org/frontpage',
'https://rss.cnn.com/rss/edition.rss',
'https://feeds.bbci.co.uk/news/rss.xml'
],
keyword: 'technology',
limit: 10
});
// Filter by custom fields
const filteredItems = await rssSkill.fetchFeed('https://example.com/feed', {
fields: ['title', 'link', 'pubDate', 'contentSnippet'],
limit: 5
});
// Enable summarization (stub for future AI integration)
const summarizedItems = await rssSkill.fetchFeed('https://example.com/feed', {
summarize: true,
limit: 3
});RssFetcherSkill Key Features
- โ Single and multi-feed fetching
- โ Keyword-based filtering
- โ Date-based filtering
- โ Custom field selection
- โ Feed aggregation
- โ Error handling and retries
- โ Future AI summarization support
WebSearchSkill
AI-powered web search with intelligent analysis, result summarization, and recommendations.
WebSearchSkill Setup
import { WebSearchSkill } from '@agentdao/core';WebSearchSkill Configuration
const webSearchConfig = {
agentId: 'web-search-agent',
agentName: 'Web Search Agent',
domain: 'search.agentdao.com',
ai: {
provider: 'openai',
model: 'gpt-4',
apiKey: process.env.OPENAI_API_KEY,
maxTokens: 2000,
temperature: 0.7
},
search: {
provider: 'google', // or 'bing', 'duckduckgo'
apiKey: process.env.GOOGLE_API_KEY,
maxResults: 10,
includeImages: true,
includeNews: true
},
integration: {
webhooks: {
enabled: true,
url: 'https://example.com/webhook'
}
},
analytics: {
enabled: true,
tracking: ['searches', 'results', 'user_queries']
}
};WebSearchSkill Usage
const webSearchSkill = new WebSearchSkill(webSearchConfig);
// Basic web search
const searchResults = await webSearchSkill.searchWeb({
query: 'AI agents and machine learning',
maxResults: 10
});
// AI-powered search with analysis
const aiResults = await webSearchSkill.searchWithAI(
'What are the latest developments in AI?',
'Focus on recent breakthroughs in 2024'
);
// News search
const newsResults = await webSearchSkill.searchNews('AI regulation', {
maxResults: 5,
timeRange: 'week',
language: 'en'
});
// Image search
const imageResults = await webSearchSkill.searchImages('AI robots', {
maxResults: 10,
size: 'large',
type: 'photo'
});
// Get search analytics
const analytics = await webSearchSkill.getSearchAnalytics();
// Validate search query
const validation = webSearchSkill.validateQuery('AI agents');
if (validation.isValid) {
// Proceed with search
} else {
console.log('Query errors:', validation.errors);
}WebSearchSkill Key Features
- โ Multi-provider search (Google, Bing, DuckDuckGo)
- โ AI-powered result analysis
- โ Intelligent summarization
- โ News and image search
- โ Query validation and security
- โ Search analytics and tracking
- โ Webhook integrations
- โ Harmful content filtering
Core Agent Usage
import { Agent } from '@agentdao/core';
// Create a new agent
const agent = new Agent({
name: 'my-agent',
description: 'A custom agent',
version: '1.0.0',
handler: async (input) => {
// Process the input
return { result: 'success' };
},
});
// Execute the agent
try {
const result = await agent.execute({ query: 'test' });
console.log(result);
} catch (error) {
console.error('Agent execution failed:', error);
}API Reference
Agent
The main class for creating and executing agents.
Constructor
new Agent(config: AgentConfig)Configuration
interface AgentConfig {
name: string;
handler: (input: AgentInput) => Promise<AgentOutput>;
description?: string;
version?: string;
validateInput?: (input: AgentInput) => boolean;
validateOutput?: (output: AgentOutput) => boolean;
}Methods
execute(input: AgentInput): Promise<AgentOutput>getName(): stringgetDescription(): string | undefinedgetVersion(): string | undefinedgetMetadata(): AgentMetadata
Types
AgentInput: The input type for agent executionAgentOutput: The output type for agent executionAgentError: Standardized error typeAgentMetadata: Agent metadata including creation and update timestamps
Development
# Install dependencies
pnpm install
# Run tests
pnpm test
# Build the package
pnpm build
# Run linting
pnpm lint
# Format code
pnpm format๐ Changelog
v0.4.2 (Latest)
- ๐ง FundAgent Enhanced: Added rate limiting, retry logic, and fallback mechanisms
- ๐ค ContentGeneratorSkill Improved: Enhanced error handling, validation, and retry mechanisms
- โก Production Ready: 9/10 skills now production-ready with real implementations
- ๐งช Comprehensive Testing: 33 tests passing with full coverage
- ๐ก๏ธ Error Handling: Improved error handling across all skills with graceful fallbacks
- ๐ Rate Limiting: Smart rate limiting for blockchain and API calls
- ๐ Test Address Detection: Automatic detection and handling of test environments
v0.4.1
- Initial release with core skills
- Basic functionality for all skills
- TypeScript support and type definitions
License
MIT
API Key Requirement
You must provide your AgentDAO API key to use the AgentBridgeClient and access the AgentDAO API.
Example Usage
import { AgentBridgeClient } from '@agentdao/core';
const client = new AgentBridgeClient(
process.env.NEXT_PUBLIC_API_URL!,
process.env.AGENTDAO_API_KEY // Your AgentDAO API key
);- Set
NEXT_PUBLIC_API_URLandAGENTDAO_API_KEYin your environment variables or.envfile.
FundAgent
Autonomously creates Gnosis Safe wallets for projects or domains when funded with ADAO tokens. Useful for reward pools, DAOs, and agent-managed funds. Now with enhanced reliability, rate limiting, and fallback mechanisms.
๐ FundAgent v0.4.2 Improvements
- ๐ก๏ธ Rate Limiting: Configurable rate limiting (30 requests/minute default)
- ๐ Retry Logic: Exponential backoff with smart error detection
- ๐ ๏ธ Fallback Mechanisms: Graceful degradation when blockchain calls fail
- ๐งช Test Environment Support: Automatic detection and mock responses for test addresses
- ๐ Error Handling: Comprehensive error logging and recovery
- โก Performance: Optimized blockchain interactions with caching
FundAgent Setup
import { FundAgent } from '@agentdao/core';
const fundAgent = new FundAgent({
// Chain configuration
chainId: 8453, // Base chain
network: 'base',
rpcUrl: 'https://mainnet.base.org',
// Token configuration
tokenAddress: '0x1ef7Be0aBff7d1490e952eC1C7476443A66d6b72', // ADAO token
tokenSymbol: 'ADAO',
tokenDecimals: 18,
// Safe wallet configuration
safeFactoryAddress: '0xSAFEFACTORY...', // Optional: Safe Factory contract
minDeposit: 100, // Minimum ADAO tokens required
// Agent configuration
agentAddress: '0xAgentContract...',
// Rate limiting configuration (optional)
rateLimit: {
maxRequestsPerMinute: 30,
retryAttempts: 3,
retryDelayMs: 1000
},
// Database configuration (optional)
database: {
endpoint: 'https://your-api.com/database',
apiKey: 'your-api-key'
}
});FundAgent Usage
// Verify payment (with rate limiting and retry logic)
const hasPayment = await fundAgent.verifyPayment('0xUserWallet...');
// Get token balance (with fallback mechanisms)
const balance = await fundAgent.getTokenBalance('0xUserWallet...');
// Create Safe wallet (with database fallback)
const safeAddress = await fundAgent.createSafeWallet('0xUserWallet...', 100);
// Get wallet status (with test address detection)
const status = await fundAgent.getWalletStatus(safeAddress);
// Add a new owner to Safe wallet
await fundAgent.addOwner(safeAddress, '0xNewOwner...');FundAgent Key Features
- โ Rate Limiting: Prevents API rate limit issues
- โ Retry Logic: Automatic retry with exponential backoff
- โ Test Environment Support: Mock responses for development
- โ Fallback Mechanisms: Database fallbacks when blockchain fails
- โ Error Recovery: Graceful handling of network issues
- โ Safe Wallet Management: Create and manage Gnosis Safe wallets
- โ Token Verification: Verify ADAO token payments
- โ Multi-Chain Support: Works on any EVM-compatible chain
Key Features
- โ Autonomous Safe wallet creation
- โ Multi-owner (multi-sig) support
- โ ADAO token funding and gating
- โ API for wallet status and management
- โ Integrates with other agents (e.g., GamificationAgent)
LiveChatWidget
Real-time chat widget with AI-powered responses. Now supports real AI integration using your API keys!
LiveChatWidget Setup
import { LiveChatWidget } from '@agentdao/core';LiveChatWidget Configuration
const chatConfig = {
agentId: 'my-chat-agent',
agentName: 'My AI Assistant',
domain: 'myapp.com',
// AI Configuration
ai: {
provider: 'openai',
model: 'gpt-3.5-turbo',
temperature: 0.7,
maxTokens: 500,
systemPrompt: 'You are a helpful AI assistant for our platform. Be friendly and provide useful information.'
},
// UI Configuration
theme: 'dark',
position: 'bottom-right',
welcomeMessage: 'Hello! How can I help you today?',
showAvatar: true,
showTypingIndicator: true,
autoScroll: true,
maxMessages: 50,
// Event Handlers
onMessageSent: (message) => console.log('Message sent:', message),
onMessageReceived: (message) => console.log('Message received:', message),
onChatStarted: () => console.log('Chat started'),
onChatEnded: () => console.log('Chat ended')
};LiveChatWidget Usage
import { LiveChatWidget } from '@agentdao/core';
function MyApp() {
return (
<div>
<h1>My App</h1>
<p>Welcome to our platform!</p>
{/* LiveChatWidget with real AI */}
<LiveChatWidget config={chatConfig} />
</div>
);
}LiveChatWidget Features
- โ Real AI responses using OpenAI API
- โ Conversation context - remembers previous messages
- โ Configurable AI settings - model, temperature, system prompt
- โ Error handling - graceful fallbacks for API failures
- โ Typing indicators - shows when AI is thinking
- โ Message status - sending, sent, error states
- โ Customizable UI - themes, position, styling
- โ Event callbacks - track user interactions
API Key Setup
The LiveChatWidget automatically uses your OpenAI API key from:
- Settings > API Keys in your AgentDAO dashboard
- Environment variables in your project
- Custom configuration passed to the widget
Example: Custom AI Configuration
const customChatConfig = {
agentId: 'support-chat',
agentName: 'Customer Support Bot',
domain: 'support.company.com',
ai: {
provider: 'openai',
model: 'gpt-4',
temperature: 0.3, // More focused responses
maxTokens: 1000, // Longer responses
systemPrompt: `You are a customer support specialist for Company XYZ.
Your role is to help customers with technical issues, billing questions, and product support.
Always be polite, professional, and provide step-by-step solutions when possible.
If you cannot help, escalate to human support.`
},
theme: 'light',
position: 'bottom-left',
welcomeMessage: 'Hi! I\'m here to help with any questions or issues you might have.'
};