sentilyze 2.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (4) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +305 -0
  3. package/index.js +174 -0
  4. package/package.json +38 -0
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2025 Sentilyze.ai
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,305 @@
1
+ # Sentilyze SDK
2
+
3
+ Official Node.js SDK for [Sentilyze.ai](https://sentilyze.ai) - Transform customer feedback into actionable insights with AI-powered sentiment analysis.
4
+
5
+ [![npm version](https://img.shields.io/npm/v/sentilyze.svg)](https://www.npmjs.com/package/sentilyze)
6
+ [![License: MIT](https://img.shields.io/badge/License-MIT-blue.svg)](https://opensource.org/licenses/MIT)
7
+
8
+ ## Installation
9
+
10
+ ```bash
11
+ npm install sentilyze
12
+ ```
13
+
14
+ ## Quick Start
15
+
16
+ ```javascript
17
+ const SentilyzeClient = require('sentilyze');
18
+
19
+ // Initialize the client with your API key
20
+ const client = new SentilyzeClient({
21
+ apiKey: 'senti_your_api_key_here'
22
+ });
23
+
24
+ // Analyze sentiment
25
+ const result = await client.analyze('This product is amazing!');
26
+ console.log(result);
27
+ ```
28
+
29
+ **Response:**
30
+ ```javascript
31
+ {
32
+ sentiment: 'positive',
33
+ score: 5.2,
34
+ summary: 'Customer expresses high satisfaction with the product',
35
+ tags: ['product', 'satisfaction', 'quality'],
36
+ usage: {
37
+ requestsUsed: 1,
38
+ requestsLimit: 1000,
39
+ requestsRemaining: 999,
40
+ subscriptionPlan: 'Starter',
41
+ resetDate: '2025-12-31T23:59:59.999Z'
42
+ }
43
+ }
44
+ ```
45
+
46
+ ## Features
47
+
48
+ - ✅ **Sentiment Analysis** - Detect positive, negative, or neutral sentiment
49
+ - ✅ **Happiness Scoring** - Measure happiness levels from 1-6 scale
50
+ - ✅ **AI-Powered Summary** - Get concise summaries of feedback
51
+ - ✅ **Tag Extraction** - Automatic keyword and topic extraction
52
+ - ✅ **Batch Processing** - Analyze multiple texts efficiently
53
+ - ✅ **Usage Tracking** - Monitor your API usage in real-time
54
+ - ✅ **Error Handling** - Comprehensive error messages and retry logic
55
+
56
+ ## API Reference
57
+
58
+ ### Initialize Client
59
+
60
+ ```javascript
61
+ const client = new SentilyzeClient({
62
+ apiKey: 'senti_your_api_key', // Required: Your API key
63
+ baseUrl: 'https://api.sentilyze.ai', // Optional: Custom API URL
64
+ timeout: 30000 // Optional: Request timeout (ms)
65
+ });
66
+ ```
67
+
68
+ ### Analyze Text
69
+
70
+ Analyze a single text for sentiment and happiness:
71
+
72
+ ```javascript
73
+ // Simple string
74
+ const result = await client.analyze('Customer feedback text');
75
+
76
+ // With options object
77
+ const result = await client.analyze({
78
+ feedback: 'Customer feedback text'
79
+ });
80
+ ```
81
+
82
+ **Response Structure:**
83
+ ```javascript
84
+ {
85
+ sentiment: 'positive' | 'negative' | 'neutral',
86
+ score: number, // 1-6 scale (decimal)
87
+ summary: string, // AI-generated summary
88
+ tags: string[], // Extracted keywords
89
+ usage: {
90
+ requestsUsed: number,
91
+ requestsLimit: number | 'unlimited',
92
+ requestsRemaining: number | 'unlimited',
93
+ subscriptionPlan: string,
94
+ resetDate: string
95
+ }
96
+ }
97
+ ```
98
+
99
+ **Example:**
100
+ ```javascript
101
+ const result = await client.analyze('The product quality is excellent, but shipping was slow');
102
+
103
+ console.log(result.sentiment); // 'positive'
104
+ console.log(result.score); // 4.5
105
+ console.log(result.summary); // 'Mixed feedback with product praise and shipping concerns'
106
+ console.log(result.tags); // ['product', 'quality', 'shipping', 'delivery']
107
+ ```
108
+
109
+ ### Batch Analysis
110
+
111
+ Analyze multiple texts efficiently with concurrency control:
112
+
113
+ ```javascript
114
+ const texts = [
115
+ 'Great service!',
116
+ 'Not satisfied',
117
+ 'Could be better',
118
+ 'Excellent product!'
119
+ ];
120
+
121
+ const result = await client.batchAnalyze(texts, {
122
+ concurrency: 5 // Optional: Number of parallel requests (default: 5)
123
+ });
124
+
125
+ console.log(result);
126
+ ```
127
+
128
+ **Response Structure:**
129
+ ```javascript
130
+ {
131
+ results: [ // Array of successful analysis results
132
+ {
133
+ sentiment: 'positive',
134
+ score: 5.8,
135
+ summary: '...',
136
+ tags: [...],
137
+ usage: {...}
138
+ },
139
+ // ... more results
140
+ ],
141
+ errors: [], // Array of failed analyses with error details
142
+ totalProcessed: 4, // Total texts processed
143
+ successCount: 4, // Number of successful analyses
144
+ errorCount: 0 // Number of failed analyses
145
+ }
146
+ ```
147
+
148
+ **Example:**
149
+ ```javascript
150
+ const texts = ['Happy customer!', 'Very disappointed', 'It works fine'];
151
+ const result = await client.batchAnalyze(texts);
152
+
153
+ console.log(`Successfully analyzed ${result.successCount}/${result.totalProcessed} texts`);
154
+
155
+ // Calculate average score
156
+ const avgScore = result.results.reduce((sum, r) => sum + r.score, 0) / result.results.length;
157
+ console.log(`Average score: ${avgScore.toFixed(1)}/6`);
158
+ ```
159
+
160
+ ### Get Usage Statistics
161
+
162
+ Check your current API usage:
163
+
164
+ ```javascript
165
+ const usage = await client.getUsage();
166
+ console.log(usage);
167
+ ```
168
+
169
+ **Response:**
170
+ ```javascript
171
+ {
172
+ data: {
173
+ requestsUsed: 150,
174
+ requestsLimit: 1000,
175
+ requestsRemaining: 850,
176
+ subscriptionPlan: 'Starter',
177
+ resetDate: '2025-12-31T23:59:59.999Z',
178
+ currentPeriod: {
179
+ month: 12,
180
+ year: 2025
181
+ }
182
+ }
183
+ }
184
+ ```
185
+
186
+ ## Error Handling
187
+
188
+ The SDK provides detailed error handling:
189
+
190
+ ```javascript
191
+ try {
192
+ const result = await client.analyze('Text to analyze');
193
+ } catch (error) {
194
+ if (error.status === 401) {
195
+ console.error('Invalid API key');
196
+ } else if (error.status === 429) {
197
+ console.error('Rate limit exceeded');
198
+ } else if (error.message.includes('timeout')) {
199
+ console.error('Request timed out');
200
+ } else if (error.message.includes('Network error')) {
201
+ console.error('Cannot reach API');
202
+ } else {
203
+ console.error('Analysis failed:', error.message);
204
+ }
205
+ }
206
+ ```
207
+
208
+ ## Common Use Cases
209
+
210
+ ### Customer Feedback Analysis
211
+ ```javascript
212
+ // Analyze customer review
213
+ const review = await client.analyze(
214
+ 'The product quality is excellent, but shipping was slow'
215
+ );
216
+
217
+ if (review.sentiment === 'positive') {
218
+ console.log(`Happy customer! Score: ${review.score}/6`);
219
+ console.log(`Summary: ${review.summary}`);
220
+ console.log(`Topics: ${review.tags.join(', ')}`);
221
+ }
222
+ ```
223
+
224
+ ### Bulk Survey Processing
225
+ ```javascript
226
+ // Process survey responses
227
+ const responses = [
228
+ 'Great experience overall',
229
+ 'Service needs improvement',
230
+ 'Product exceeded expectations'
231
+ ];
232
+
233
+ const result = await client.batchAnalyze(responses);
234
+ console.log(`Analyzed ${result.successCount} responses`);
235
+
236
+ // Calculate average happiness
237
+ const avgScore = result.results.reduce(
238
+ (sum, r) => sum + r.score, 0
239
+ ) / result.results.length;
240
+
241
+ console.log(`Average satisfaction: ${avgScore.toFixed(1)}/6`);
242
+
243
+ // Count sentiments
244
+ const sentiments = result.results.reduce((acc, r) => {
245
+ acc[r.sentiment] = (acc[r.sentiment] || 0) + 1;
246
+ return acc;
247
+ }, {});
248
+
249
+ console.log('Sentiment distribution:', sentiments);
250
+ // { positive: 2, negative: 1 }
251
+ ```
252
+
253
+ ### Real-time Feedback Monitoring
254
+ ```javascript
255
+ // Monitor new feedback in real-time
256
+ async function processNewFeedback(feedbackText) {
257
+ const result = await client.analyze(feedbackText);
258
+
259
+ // Alert on negative feedback
260
+ if (result.sentiment === 'negative' && result.score < 3) {
261
+ console.warn('⚠️ Negative feedback detected!');
262
+ console.warn(`Score: ${result.score}/6`);
263
+ console.warn(`Summary: ${result.summary}`);
264
+ // Trigger notification to support team
265
+ }
266
+
267
+ return result;
268
+ }
269
+ ```
270
+
271
+ ## Subscription Plans
272
+
273
+ | Plan | Requests/Month | Price | Best For |
274
+ |------|----------------|-------|----------|
275
+ | Developer | 100 | Free | Testing & development |
276
+ | Starter | 1,000 | $29 | Small projects |
277
+ | Professional | 10,000 | $199 | Growing businesses |
278
+ | Enterprise | Unlimited | Custom | Large organizations |
279
+
280
+ Get your API key at [sentilyze.ai](https://sentilyze.ai)
281
+
282
+ ## Response Field Descriptions
283
+
284
+ - **sentiment**: Classification of the feedback (`positive`, `negative`, or `neutral`)
285
+ - **score**: Happiness/satisfaction score on a 1-6 scale (decimal values like 4.5 are supported)
286
+ - 1-2: Very unhappy
287
+ - 3-4: Neutral to slightly satisfied
288
+ - 5-6: Very happy
289
+ - **summary**: AI-generated concise summary of the feedback
290
+ - **tags**: Array of extracted keywords and topics from the text
291
+ - **usage**: Current API usage information for rate limiting and billing
292
+
293
+ ## Support
294
+
295
+ - 📧 Email: support@sentilyze.ai
296
+ - 🌐 Website: https://www.sentilyze.ai
297
+ - 📚 Dashboard: https://www.sentilyze.ai/dashboard
298
+
299
+ ## License
300
+
301
+ MIT © Sentilyze.ai
302
+
303
+ ---
304
+
305
+ Made with ❤️ by [Sentilyze.ai](https://sentilyze.ai)
package/index.js ADDED
@@ -0,0 +1,174 @@
1
+ /**
2
+ * Sentilyze SDK - Official Node.js client for Sentilyze.ai
3
+ * Analyze sentiment and happiness levels from customer feedback
4
+ * @version 2.0.0
5
+ */
6
+
7
+ class SentilyzeClient {
8
+ /**
9
+ * Create a Sentilyze client instance
10
+ * @param {Object} config - Configuration options
11
+ * @param {string} config.apiKey - Your Sentilyze API key
12
+ * @param {string} [config.baseUrl='https://api.sentilyze.ai'] - API base URL
13
+ * @param {number} [config.timeout=30000] - Request timeout in milliseconds
14
+ */
15
+ constructor(config) {
16
+ if (!config || !config.apiKey) {
17
+ throw new Error('API key is required. Get yours at https://sentilyze.ai');
18
+ }
19
+
20
+ this.apiKey = config.apiKey;
21
+ this.baseUrl = config.baseUrl || 'https://api.sentilyze.ai';
22
+ this.timeout = config.timeout || 30000;
23
+ }
24
+
25
+ /**
26
+ * Internal method to make API requests
27
+ * @private
28
+ */
29
+ async _request(endpoint, options = {}) {
30
+ const controller = new AbortController();
31
+ const timeoutId = setTimeout(() => controller.abort(), this.timeout);
32
+
33
+ try {
34
+ const response = await fetch(`${this.baseUrl}${endpoint}`, {
35
+ ...options,
36
+ headers: {
37
+ 'Content-Type': 'application/json',
38
+ 'x-api-key': this.apiKey,
39
+ ...options.headers
40
+ },
41
+ signal: controller.signal
42
+ });
43
+
44
+ clearTimeout(timeoutId);
45
+
46
+ const data = await response.json().catch(() => null);
47
+
48
+ if (!response.ok) {
49
+ const errorMessage = data?.error?.message || data?.message || response.statusText;
50
+ const error = new Error(errorMessage);
51
+ error.status = response.status;
52
+ error.response = data;
53
+ throw error;
54
+ }
55
+
56
+ return data;
57
+ } catch (error) {
58
+ clearTimeout(timeoutId);
59
+
60
+ if (error.name === 'AbortError') {
61
+ throw new Error(`Request timeout after ${this.timeout}ms`);
62
+ }
63
+
64
+ if (error.message.includes('fetch') && !error.status) {
65
+ throw new Error('Network error: Unable to reach Sentilyze API');
66
+ }
67
+
68
+ throw error;
69
+ }
70
+ }
71
+
72
+ /**
73
+ * Analyze sentiment and happiness from text
74
+ * @param {string|Object} input - Text to analyze or options object
75
+ * @param {string} input.feedback - Text to analyze (when using options object)
76
+ * @returns {Promise<Object>} Analysis results with sentiment, score, summary, tags, and usage info
77
+ *
78
+ * @example
79
+ * const result = await client.analyze('This product is amazing!');
80
+ * console.log(result.sentiment); // 'positive'
81
+ * console.log(result.score); // 5.2
82
+ * console.log(result.summary); // 'Customer expresses high satisfaction'
83
+ * console.log(result.tags); // ['product', 'satisfaction']
84
+ * console.log(result.usage); // { requestsUsed: 1, requestsLimit: 1000, ... }
85
+ */
86
+ async analyze(input) {
87
+ const feedback = typeof input === 'string' ? input : input.feedback;
88
+
89
+ if (!feedback || typeof feedback !== 'string') {
90
+ throw new Error('Text is required for analysis');
91
+ }
92
+
93
+ if (feedback.trim().length === 0) {
94
+ throw new Error('Text cannot be empty');
95
+ }
96
+
97
+ return await this._request('/api/analyze', {
98
+ method: 'POST',
99
+ body: JSON.stringify({ feedback })
100
+ });
101
+ }
102
+
103
+ /**
104
+ * Batch analyze multiple texts (processes them in parallel)
105
+ * @param {string[]} texts - Array of texts to analyze
106
+ * @param {Object} [options] - Batch options
107
+ * @param {number} [options.concurrency=5] - Number of concurrent requests
108
+ * @returns {Promise<Object>} Object containing results array and statistics
109
+ *
110
+ * @example
111
+ * const result = await client.batchAnalyze([
112
+ * 'Great service!',
113
+ * 'Not satisfied with the product',
114
+ * 'Average experience'
115
+ * ]);
116
+ * console.log(result.successCount); // 3
117
+ * console.log(result.results[0].sentiment); // 'positive'
118
+ */
119
+ async batchAnalyze(texts, options = {}) {
120
+ if (!Array.isArray(texts) || texts.length === 0) {
121
+ throw new Error('An array of texts is required for batch analysis');
122
+ }
123
+
124
+ const concurrency = options.concurrency || 5;
125
+ const results = [];
126
+ const errors = [];
127
+
128
+ // Process in batches to respect concurrency
129
+ for (let i = 0; i < texts.length; i += concurrency) {
130
+ const batch = texts.slice(i, i + concurrency);
131
+ const batchResults = await Promise.allSettled(
132
+ batch.map((text, index) =>
133
+ this.analyze(text).catch(error => {
134
+ errors.push({ index: i + index, text, error: error.message });
135
+ return null;
136
+ })
137
+ )
138
+ );
139
+
140
+ results.push(...batchResults.map(r => r.status === 'fulfilled' ? r.value : null));
141
+ }
142
+
143
+ return {
144
+ results: results.filter(r => r !== null),
145
+ errors,
146
+ totalProcessed: texts.length,
147
+ successCount: results.filter(r => r !== null).length,
148
+ errorCount: errors.length
149
+ };
150
+ }
151
+
152
+ /**
153
+ * Get API usage statistics for your account
154
+ * @returns {Promise<Object>} Usage statistics for current period
155
+ *
156
+ * @example
157
+ * const usage = await client.getUsage();
158
+ * console.log(usage.data);
159
+ * // {
160
+ * // requestsUsed: 150,
161
+ * // requestsLimit: 1000,
162
+ * // requestsRemaining: 850,
163
+ * // subscriptionPlan: 'Starter',
164
+ * // resetDate: '2025-12-31T23:59:59.999Z'
165
+ * // }
166
+ */
167
+ async getUsage() {
168
+ return await this._request('/api/usage', {
169
+ method: 'GET'
170
+ });
171
+ }
172
+ }
173
+
174
+ module.exports = SentilyzeClient;
package/package.json ADDED
@@ -0,0 +1,38 @@
1
+ {
2
+ "name": "sentilyze",
3
+ "version": "2.0.0",
4
+ "description": "Official Node.js SDK for Sentilyze.ai - Analyze sentiment and happiness levels from customer feedback with AI",
5
+ "main": "index.js",
6
+ "scripts": {
7
+ "test": "echo \"Error: no test specified\" && exit 1"
8
+ },
9
+ "keywords": [
10
+ "sentilyze",
11
+ "sentiment",
12
+ "analysis",
13
+ "sentiment-analysis",
14
+ "happiness",
15
+ "ai",
16
+ "nlp",
17
+ "customer-feedback",
18
+ "gpt-4",
19
+ "text-analysis",
20
+ "analytics",
21
+ "insights",
22
+ "word-cloud",
23
+ "customer-satisfaction"
24
+ ],
25
+ "author": "Sentilyze.ai",
26
+ "license": "MIT",
27
+ "repository": {
28
+ "type": "git",
29
+ "url": "https://github.com/yourusername/sentilyze-sdk.git"
30
+ },
31
+ "bugs": {
32
+ "url": "https://github.com/yourusername/sentilyze-sdk/issues"
33
+ },
34
+ "homepage": "https://sentilyze.ai",
35
+ "engines": {
36
+ "node": ">=18.0.0"
37
+ }
38
+ }