ToneConsistencyMetric
The ToneConsistencyMetric
class evaluates the emotional tone and sentiment consistency in text. It can operate in two modes: comparing tone between input/output pairs, or analyzing tone stability within a single text.
Basic Usage
import { ToneConsistencyMetric } from "@mastra/evals/nlp";
const metric = new ToneConsistencyMetric();
// Compare tone between input and output
const result1 = await metric.measure(
"I love this amazing product!",
"This product is wonderful and fantastic!"
);
// Analyze tone stability in a single text
const result2 = await metric.measure(
"The service is excellent. The staff is friendly. The atmosphere is perfect.",
"" // Empty string for single-text analysis
);
console.log(result1.score); // Tone consistency score from 0-1
console.log(result2.score); // Tone stability score from 0-1
measure() Parameters
input:
string
The text to analyze for tone
output:
string
Reference text for tone comparison (empty string for stability analysis)
Returns
score:
number
Tone consistency/stability score (0-1)
info:
object
Detailed tone info
info Object (Tone Comparison)
responseSentiment:
number
Sentiment score for the input text
referenceSentiment:
number
Sentiment score for the output text
difference:
number
Absolute difference between sentiment scores
info Object (Tone Stability)
avgSentiment:
number
Average sentiment score across sentences
sentimentVariance:
number
Variance in sentiment between sentences
Modes of Operation
1. Tone Consistency (with reference)
When both input and output are provided:
- Compares sentiment between the two texts
- Calculates sentiment difference
- Higher score indicates more consistent tone
2. Tone Stability (single input)
When output is empty:
- Analyzes sentiment stability across sentences
- Calculates variance in sentiment
- Higher score indicates more stable tone
Example with Both Modes
const metric = new ToneConsistencyMetric();
// Tone Consistency Mode
const consistencyResult = await metric.measure(
"This product is fantastic and amazing!",
"The product is excellent and wonderful!"
);
// Example output:
// {
// score: 0.95,
// info: {
// responseSentiment: 0.8,
// referenceSentiment: 0.75,
// difference: 0.05
// }
// }
// Tone Stability Mode
const stabilityResult = await metric.measure(
"Great service! Friendly staff. Perfect atmosphere.",
""
);
// Example output:
// {
// score: 0.9,
// info: {
// avgSentiment: 0.6,
// sentimentVariance: 0.1
// }
// }