withwebmind
v2.1.1
Published
The easiest way to add AI to your website - Official WebMind SDK with AI training data collection
Maintainers
Readme
WebMind SDK
🚀 The easiest way to add AI to your website
The official WebMind SDK provides simple, powerful integration with AI models from OpenAI, Anthropic, Google, and more through a unified API.
✨ Features
- 🎯 Simple Integration - Add AI to your website in minutes
- 🤖 Multiple AI Providers - Access GPT-4, Claude 3, Gemini Pro, and 50+ models
- 🔄 Automatic Failover - Never worry about downtime
- 💰 Transparent Pricing - Clear usage and billing
- 🔒 Enterprise Security - Bank-level security and encryption
- 📊 Real-time Analytics - Monitor usage and performance
- 🧠 AI Training Support - Contribute to AI improvement with anonymized data collection (opt-in)
🚀 Quick Start
Installation
npm install withwebmindBasic Usage
import { WebMind } from 'withwebmind'
const ai = new WebMind('your-api-key-here')
// Simple query
const response = await ai.query('Hello, how are you?')
console.log(response.response)Advanced Usage
import { WebMind } from 'withwebmind'
const ai = new WebMind('your-api-key', {
baseUrl: 'https://api.withwebmind.com',
timeout: 30000,
retries: 3
})
// Query with options
const response = await ai.query('Write a haiku about programming', {
model: 'gpt-4',
temperature: 0.8,
maxTokens: 200,
systemPrompt: 'You are a creative poet who loves technology'
})
console.log(response.response)
console.log(`Cost: $${response.cost}`)
console.log(`Tokens used: ${response.usage?.totalTokens}`)Data Collection for AI Training
Help improve AI models by opting into anonymized data collection. Your personal information is never stored.
// Enable data collection for AI training
const response = await ai.query('Explain quantum computing', {
model: 'gpt-4',
dataCollection: {
enabled: true,
// Optional: provide custom anonymized user ID
anonymizedUserId: 'user_anonymous_123',
// Optional: additional metadata
metadata: {
category: 'education',
difficulty: 'intermediate'
}
}
})📚 API Reference
WebMind Class
Constructor
const ai = new WebMind(apiKey: string, config?: WebMindConfig)Parameters:
apiKey(string): Your WebMind API keyconfig(optional): Configuration options
Config Options:
interface WebMindConfig {
baseUrl?: string // API base URL (default: 'https://api.withwebmind.com')
timeout?: number // Request timeout in ms (default: 30000)
retries?: number // Number of retries on failure (default: 3)
}Methods
query(prompt, options?)
Query the AI with a prompt.
const response = await ai.query(prompt: string, options?: QueryOptions): Promise<QueryResponse>Parameters:
prompt(string): The prompt to send to the AIoptions(optional): Query configuration options
Options:
interface QueryOptions {
model?: string // AI model to use (default: 'gpt-3.5-turbo')
temperature?: number // Creativity (0-2, default: 0.7)
maxTokens?: number // Maximum response length (default: 1000)
systemPrompt?: string // System message for context
stream?: boolean // Enable streaming response
webhookUrl?: string // Webhook URL for notifications
metadata?: object // Additional metadata
dataCollection?: { // AI training data collection (opt-in)
enabled?: boolean // Enable anonymized data collection
anonymizedUserId?: string // Custom anonymous user ID
metadata?: object // Additional training metadata
}
}Returns:
interface QueryResponse {
id: string // Unique response ID
response: string // AI response text
model: string // Model used
usage?: {
promptTokens: number
completionTokens: number
totalTokens: number
}
cost: number // Cost in USD
responseTime: number // Response time in ms
timestamp: string // ISO timestamp
}getUsage()
Get current usage statistics.
const usage = await ai.getUsage()
console.log(`Credits: $${usage.credits}`)
console.log(`Spent this month: $${usage.totalSpent}`)addCredits(amount)
Add credits to your account.
const result = await ai.addCredits(10)
console.log(`New balance: $${result.newBalance}`)🌐 HTTP API
If you prefer to use HTTP requests directly:
Query Endpoint
curl -X POST https://api.withwebmind.com/v1/query \\
-H "Authorization: Bearer YOUR_API_KEY" \\
-H "Content-Type: application/json" \\
-d '{
"prompt": "Hello, world!",
"model": "gpt-4",
"temperature": 0.7
}'Response Format
{
"success": true,
"data": {
"id": "query_123",
"response": "Hello! How can I help you today?",
"model": "gpt-4",
"usage": {
"promptTokens": 10,
"completionTokens": 8,
"totalTokens": 18
},
"cost": 0.001,
"responseTime": 450,
"timestamp": "2024-01-01T12:00:00.000Z"
}
}🔧 Model Support
Free Models (No credits required)
meta-llama/llama-3.1-8b-instruct:freemicrosoft/wizardlm-2-8x22bgoogle/gemma-7b-it:free
Paid Models (Credits required)
openai/gpt-4openai/gpt-3.5-turboanthropic/claude-3-opusanthropic/claude-3-sonnetgoogle/gemini-prometa-llama/llama-3.1-70b-instruct
💰 Pricing
- Free Tier: 1,000 requests/month
- Paid Models: ~$0.045 per request (varies by model)
- Credits: $1 = 100 credits (never expire)
- No Hidden Fees: Transparent pricing with real-time cost calculation
🔒 Security
- API Key Authentication: Secure Bearer token authentication
- End-to-End Encryption: All requests encrypted in transit
- Rate Limiting: Built-in protection against abuse
- Audit Logging: Complete request/response logging
🚨 Error Handling
The SDK includes comprehensive error handling:
try {
const response = await ai.query('Hello')
} catch (error) {
if (error instanceof WebMindError) {
console.log('Error code:', error.code)
console.log('Status code:', error.statusCode)
}
}Common Error Codes
MISSING_API_KEY: No API key providedINVALID_API_KEY: Invalid API keyINSUFFICIENT_CREDITS: Not enough creditsRATE_LIMIT_EXCEEDED: Too many requestsMODEL_NOT_FOUND: Requested model unavailable
📊 Webhooks
Set up webhooks to receive real-time notifications:
const response = await ai.query('Hello', {
webhookUrl: 'https://your-site.com/webhook',
metadata: { userId: '123' }
})Webhook Payload
{
"event": "query.completed",
"data": {
"id": "query_123",
"response": "Hello! How can I help?",
"cost": 0.001
},
"metadata": {
"userId": "123"
}
}🎯 Examples
Chatbot Integration
import { WebMind } from 'withwebmind'
const ai = new WebMind('your-api-key')
// Add to your chat interface
async function sendMessage(message: string) {
try {
const response = await ai.query(message, {
model: 'gpt-4',
temperature: 0.7
})
return response.response
} catch (error) {
console.error('Chat error:', error)
return 'Sorry, I encountered an error. Please try again.'
}
}Content Generation
const ai = new WebMind('your-api-key')
const blogPost = await ai.query('Write a blog post about AI in healthcare', {
model: 'claude-3-sonnet',
maxTokens: 1500,
systemPrompt: 'You are a professional healthcare technology writer'
})Code Assistant
const ai = new WebMind('your-api-key')
const codeHelp = await ai.query('How do I implement a binary search in Python?', {
model: 'gpt-4',
temperature: 0.3
})🛠️ Support
📄 License
MIT License - see LICENSE file for details.
Made with ❤️ by the WebMind team
