@macroprompt/sdk
v1.0.1
Published
Official JavaScript SDK for MacroPrompt - Create, manage, and execute webhooks with ease
Maintainers
Readme
MacroPrompt SDK
Official JavaScript SDK for MacroPrompt - Create, manage, and execute webhooks with ease.
Note: This SDK is ready for use. If you encounter connection issues, it may be because the API endpoints are still being configured on the server side.
Installation
npm install @macroprompt/sdkUsage
const MacroPrompt = require('@macroprompt/sdk');
// Initialize the client with your API key
const client = new MacroPrompt({
apiKey: 'mp_your_api_key_here'
});
// Test the connection
const connectionTest = await client.testConnection();
console.log('Connection:', connectionTest);
// Get all webhooks
const webhooks = await client.getWebhooks();
console.log('Webhooks:', webhooks);
// Create a new webhook
const newWebhook = await client.createWebhook({
title: 'My Webhook',
prompt: 'You are a helpful assistant. Respond to: {{input}}',
inputs: [{ name: 'input', type: 'text' }]
});
// Execute a webhook
const result = await client.executeWebhook('webhook-id', {
input: 'Hello World'
});
console.log('Result:', result);Configuration
Constructor Options
const client = new MacroPrompt({
apiKey: 'your-api-key', // Required: Your MacroPrompt API key
baseUrl: 'https://macroprompt.cloud' // Optional: Custom API base URL
});API Reference
Webhook Execution
executeWebhook(webhookId, inputs)
Execute a webhook by its ID.
const result = await client.executeWebhook('webhook-123', {
name: 'John Doe',
email: '[email protected]'
});Parameters:
webhookId(string): The webhook IDinputs(object): Input data for the webhook
Returns: Promise resolving to webhook execution result
executeWebhookByName(webhookName, inputs)
Execute a webhook by its name.
const result = await client.executeWebhookByName('Email Generator', {
recipient: 'John Doe',
subject: 'Welcome'
});Webhook Management
getWebhooks()
Get all your webhooks.
const webhooks = await client.getWebhooks();
console.log(`You have ${webhooks.length} webhooks`);getWebhook(webhookId)
Get a specific webhook by ID.
const webhook = await client.getWebhook('webhook-123');
console.log('Webhook title:', webhook.title);createWebhook(webhookData)
Create a new webhook.
const newWebhook = await client.createWebhook({
title: 'Email Generator',
description: 'Generates professional emails',
inputs: [
{
name: 'recipient',
type: 'text',
description: 'Email recipient name',
required: true
},
{
name: 'subject',
type: 'text',
description: 'Email subject',
required: true
}
],
outputs: [
{
name: 'email_content',
type: 'text',
description: 'Generated email content'
}
],
prompt: 'Generate a professional email for {{recipient}} with subject "{{subject}}"',
model: 'gpt-4'
});updateWebhook(webhookId, webhookData)
Update an existing webhook.
const updatedWebhook = await client.updateWebhook('webhook-123', {
title: 'Updated Email Generator',
description: 'Enhanced email generation with templates'
});deleteWebhook(webhookId)
Delete a webhook.
const result = await client.deleteWebhook('webhook-123');
console.log(result.message); // 'Webhook deleted successfully'Webhook History
getWebhookHistory(webhookId, options)
Get execution history for a webhook.
const history = await client.getWebhookHistory('webhook-123', {
limit: 10,
offset: 0
});
console.log(`Last ${history.length} executions:`);
history.forEach(execution => {
console.log(`- ${execution.createdAt}: ${execution.status}`);
});Utility Methods
testConnection()
Test your API connection.
const status = await client.testConnection();
if (status.connected) {
console.log('✅ Connected to MacroPrompt API');
} else {
console.error('❌ Connection failed:', status.message);
}Examples
Basic Webhook Execution
const MacroPrompt = require('@macroprompt/sdk');
const client = new MacroPrompt({
apiKey: process.env.MACROPROMPT_API_KEY
});
async function generateContent() {
try {
// Execute a content generation webhook
const result = await client.executeWebhook('content-generator-webhook-id', {
topic: 'Artificial Intelligence',
tone: 'professional',
length: 'medium'
});
console.log('Generated content:', result.content);
return result.content;
} catch (error) {
console.error('Failed to generate content:', error.message);
throw error;
}
}
generateContent();Creating and Using a Webhook
const MacroPrompt = require('@macroprompt/sdk');
const client = new MacroPrompt({
apiKey: process.env.MACROPROMPT_API_KEY
});
async function createAndUseWebhook() {
try {
// Create a new webhook
const webhook = await client.createWebhook({
title: 'Product Description Generator',
description: 'Generates compelling product descriptions',
inputs: [
{
name: 'product_name',
type: 'text',
description: 'Name of the product',
required: true
},
{
name: 'features',
type: 'array',
description: 'List of product features',
required: true
},
{
name: 'target_audience',
type: 'text',
description: 'Target customer demographic',
required: false,
default: 'general consumers'
}
],
outputs: [
{
name: 'description',
type: 'text',
description: 'Generated product description'
},
{
name: 'key_benefits',
type: 'array',
description: 'List of key product benefits'
}
],
prompt: `Create a compelling product description for {{product_name}}.
Features: {{features}}
Target Audience: {{target_audience}}
Generate an engaging description that highlights the key benefits and appeals to the target audience.`,
model: 'gpt-4'
});
console.log('Created webhook:', webhook.title);
// Use the newly created webhook
const result = await client.executeWebhook(webhook.id, {
product_name: 'Smart Fitness Tracker',
features: ['Heart rate monitoring', 'GPS tracking', 'Sleep analysis', 'Waterproof design'],
target_audience: 'fitness enthusiasts'
});
console.log('Generated description:', result.description);
console.log('Key benefits:', result.key_benefits);
} catch (error) {
console.error('Error:', error.message);
}
}
createAndUseWebhook();Batch Processing with Webhooks
const MacroPrompt = require('@macroprompt/sdk');
const client = new MacroPrompt({
apiKey: process.env.MACROPROMPT_API_KEY
});
async function batchProcess() {
const items = [
{ title: 'AI in Healthcare', category: 'technology' },
{ title: 'Sustainable Energy Solutions', category: 'environment' },
{ title: 'Remote Work Best Practices', category: 'business' }
];
const results = [];
for (const item of items) {
try {
const result = await client.executeWebhook('blog-post-generator', {
title: item.title,
category: item.category,
word_count: 500
});
results.push({
title: item.title,
content: result.blog_post,
success: true
});
console.log(`✅ Generated blog post for: ${item.title}`);
} catch (error) {
results.push({
title: item.title,
error: error.message,
success: false
});
console.error(`❌ Failed to generate blog post for: ${item.title}`);
}
}
return results;
}
batchProcess().then(results => {
const successful = results.filter(r => r.success).length;
console.log(`\nCompleted: ${successful}/${results.length} blog posts generated`);
});Error Handling
The SDK throws descriptive errors that you can catch and handle:
try {
const result = await client.executeWebhook('invalid-id', {});
} catch (error) {
if (error.message.includes('404')) {
console.error('Webhook not found');
} else if (error.message.includes('401')) {
console.error('Invalid API key');
} else if (error.message.includes('rate limit')) {
console.error('Rate limit exceeded, please try again later');
} else {
console.error('Unexpected error:', error.message);
}
}TypeScript Support
The SDK includes TypeScript definitions:
import MacroPrompt, { WebhookData, Webhook } from '@macroprompt/sdk';
const client = new MacroPrompt({
apiKey: process.env.MACROPROMPT_API_KEY!
});
const webhookData: WebhookData = {
title: 'My Webhook',
description: 'A sample webhook',
inputs: [
{
name: 'input1',
type: 'text',
required: true
}
]
};
const webhook: Webhook = await client.createWebhook(webhookData);Environment Variables
For security, store your API key in environment variables:
# .env file
MACROPROMPT_API_KEY=your-api-key-hererequire('dotenv').config();
const client = new MacroPrompt({
apiKey: process.env.MACROPROMPT_API_KEY
});Rate Limits
MacroPrompt API has rate limits. The SDK will throw an error if you exceed them. Implement retry logic with exponential backoff for production applications:
async function executeWithRetry(webhookId, inputs, maxRetries = 3) {
for (let i = 0; i < maxRetries; i++) {
try {
return await client.executeWebhook(webhookId, inputs);
} catch (error) {
if (error.message.includes('rate limit') && i < maxRetries - 1) {
const delay = Math.pow(2, i) * 1000; // Exponential backoff
console.log(`Rate limited, retrying in ${delay}ms...`);
await new Promise(resolve => setTimeout(resolve, delay));
continue;
}
throw error;
}
}
}Support
- Documentation: https://docs.macroprompt.cloud
- API Reference: https://api.macroprompt.cloud/docs
- Support: [email protected]
- GitHub Issues: https://github.com/macroprompt/macroprompt-sdk/issues
License
MIT License - see LICENSE file for details.
