@sconedev/ai_toolkit
Version:
Simplify AI integration in web apps with local and offline model support
83 lines (82 loc) • 3.08 kB
JavaScript
import { chat } from './chat';
import { getCached, setCached } from './cache';
import { getConfig } from './config';
/**
* Analyzes the sentiment of input text and returns a score from 0 to 10
* 0 = extremely negative, 5 = neutral, 10 = extremely positive
*
* @param text Text to analyze for sentiment
* @param options Additional options for sentiment analysis
* @returns A sentiment score between 0 and 10
*/
export async function analyzeSentiment(text, options) {
if (!text || text.trim().length === 0) {
throw new Error('No text provided for sentiment analysis');
}
const config = getConfig();
const cacheKey = `sentiment:${text}`;
// Check cache if enabled
if (options?.useCache !== false) {
const cached = getCached(cacheKey);
if (cached !== undefined) {
return cached;
}
}
// Notify if request tracking is enabled
if (config.onRequest) {
config.onRequest({
provider: options?.provider || config.provider,
function: 'analyzeSentiment',
input: text.length > 50 ? `${text.substring(0, 50)}...` : text
});
}
try {
// Use chat function to analyze sentiment
const customPrompt = options?.prompt ||
'Analyze the sentiment of the following text and return ONLY a single number between 0 and 10, where 0 is extremely negative, 5 is neutral, and 10 is extremely positive.';
const messages = [
{ role: 'system', content: customPrompt },
{ role: 'user', content: text }
];
const response = await chat(messages, { temperature: 0.3 });
// Extract the sentiment score from the response
const scoreMatch = response.match(/(\d+(\.\d+)?)/);
if (!scoreMatch) {
throw new Error('Failed to extract sentiment score from response');
}
let score = parseFloat(scoreMatch[0]);
// Ensure the score is within the valid range
score = Math.max(0, Math.min(10, score));
// Round to one decimal place for consistency
score = Math.round(score * 10) / 10;
// Cache the result
if (options?.useCache !== false) {
setCached(cacheKey, score);
}
return score;
}
catch (error) {
const message = error instanceof Error ? error.message : 'Unknown error';
throw new Error(`Sentiment analysis failed: ${message}`);
}
}
/**
* Returns a human-readable interpretation of the sentiment score
*
* @param score Sentiment score between 0-10
* @returns String description of the sentiment
*/
export function getSentimentLabel(score) {
if (score < 0 || score > 10) {
throw new Error('Sentiment score must be between 0 and 10');
}
if (score < 2)
return 'Very Negative';
if (score < 4)
return 'Negative';
if (score < 6)
return 'Neutral';
if (score < 8)
return 'Positive';
return 'Very Positive';
}