Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(Sentiment Analysis Node): Implement Sentiment Analysis node #10184

Merged
merged 3 commits into from
Jul 26, 2024
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,230 @@
import type {
IDataObject,
IExecuteFunctions,
INodeExecutionData,
INodeParameters,
INodeType,
INodeTypeDescription,
} from 'n8n-workflow';

import { NodeConnectionType } from 'n8n-workflow';

import type { BaseLanguageModel } from '@langchain/core/language_models/base';
import { HumanMessage } from '@langchain/core/messages';
import { SystemMessagePromptTemplate, ChatPromptTemplate } from '@langchain/core/prompts';
import { OutputFixingParser, StructuredOutputParser } from 'langchain/output_parsers';
import { z } from 'zod';
import { getTracingConfig } from '../../../utils/tracing';

const DEFAULT_SYSTEM_PROMPT_TEMPLATE =
'You are highly intelligent and accurate sentiment analyzer. Analyze the sentiment of the provided text. Categorize it into one of the following: {categories}. Use the provided formatting instructions. Only output the JSON.';

const DEFAULT_CATEGORIES = 'Positive, Neutral, Negative';
const configuredOutputs = (parameters: INodeParameters, defaultCategories: string) => {
const options = (parameters?.options ?? {}) as IDataObject;
const categories = (options?.categories as string) ?? defaultCategories;
const categoriesArray = categories.split(',').map((cat) => cat.trim());

const ret = categoriesArray.map((cat) => ({ type: NodeConnectionType.Main, displayName: cat }));
return ret;
};

export class SentimentAnalysis implements INodeType {
description: INodeTypeDescription = {
displayName: 'Sentiment Analysis',
name: 'sentimentAnalysis',
icon: 'fa:balance-scale-left',
iconColor: 'black',
group: ['transform'],
version: 1,
description: 'Analyze the sentiment of your text',
codex: {
categories: ['AI'],
subcategories: {
AI: ['Chains', 'Root Nodes'],
},
resources: {
primaryDocumentation: [
{
url: 'https://docs.n8n.io/integrations/builtin/cluster-nodes/root-nodes/n8n-nodes-langchain.chainllm/',
OlegIvaniv marked this conversation as resolved.
Show resolved Hide resolved
},
],
},
},
defaults: {
name: 'Sentiment Analysis',
},
inputs: [
{ displayName: '', type: NodeConnectionType.Main },
{
displayName: 'Model',
maxConnections: 1,
type: NodeConnectionType.AiLanguageModel,
required: true,
},
],
outputs: `={{(${configuredOutputs})($parameter, "${DEFAULT_CATEGORIES}")}}`,
properties: [
{
displayName: 'Text to Analyze',
name: 'inputText',
type: 'string',
required: true,
default: '',
description: 'Use an expression to reference data in previous nodes or enter static text',
typeOptions: {
rows: 2,
},
},
{
displayName:
'Sentiment scores are LLM-generated estimates, not statistically rigorous measurements. They may be inconsistent across runs and should be used as rough indicators only.',
name: 'detailedResultsNotice',
type: 'notice',
default: '',
displayOptions: {
show: {
'/options.includeDetailedResults': [true],
},
},
},
{
displayName: 'Options',
name: 'options',
type: 'collection',
default: {},
placeholder: 'Add Option',
options: [
{
displayName: 'Sentiment Categories',
name: 'categories',
type: 'string',
default: DEFAULT_CATEGORIES,
description: 'A comma-separated list of categories to analyze',
noDataExpression: true,
typeOptions: {
rows: 2,
},
},
{
displayName: 'System Prompt Template',
name: 'systemPromptTemplate',
type: 'string',
default: DEFAULT_SYSTEM_PROMPT_TEMPLATE,
description: 'String to use directly as the system prompt template',
typeOptions: {
rows: 6,
},
},
{
displayName: 'Include Detailed Results',
name: 'includeDetailedResults',
type: 'boolean',
default: false,
description:
'Whether to include sentiment strength and confidence scores in the output',
},
{
displayName: 'Enable Auto-Fixing',
name: 'enableAutoFixing',
type: 'boolean',
default: true,
description: 'Whether to enable auto-fixing for the output parser',
},
],
},
],
};

async execute(this: IExecuteFunctions): Promise<INodeExecutionData[][]> {
const items = this.getInputData();

const llm = (await this.getInputConnectionData(
NodeConnectionType.AiLanguageModel,
0,
)) as BaseLanguageModel;

const returnData: INodeExecutionData[][] = [];

for (let itemIdx = 0; itemIdx < items.length; itemIdx++) {
const sentimentCategories = this.getNodeParameter(
'options.categories',
itemIdx,
DEFAULT_CATEGORIES,
) as string;

const categories = sentimentCategories.split(',').map((cat) => cat.trim());
OlegIvaniv marked this conversation as resolved.
Show resolved Hide resolved

// Initialize returnData with empty arrays for each category
if (returnData.length === 0) {
returnData.push(
...Array(categories.length)
.fill([])
.map(() => []),
OlegIvaniv marked this conversation as resolved.
Show resolved Hide resolved
);
}

const options = this.getNodeParameter('options', itemIdx, {}) as {
systemPromptTemplate?: string;
includeDetailedResults?: boolean;
enableAutoFixing?: boolean;
};

const schema = z.object({
sentiment: z.enum(categories as [string, ...string[]]),
strength: z
.number()
.min(0)
.max(1)
.describe('Strength score for sentiment in relation to the category'),
confidence: z.number().min(0).max(1),
});

const structuredParser = StructuredOutputParser.fromZodSchema(schema);

const parser = options.enableAutoFixing
? OutputFixingParser.fromLLM(llm, structuredParser)
: structuredParser;

const systemPromptTemplate = SystemMessagePromptTemplate.fromTemplate(
`${options.systemPromptTemplate ?? DEFAULT_SYSTEM_PROMPT_TEMPLATE}
{format_instructions}`,
);

const input = this.getNodeParameter('inputText', itemIdx) as string;
const inputPrompt = new HumanMessage(input);
const messages = [
await systemPromptTemplate.format({
categories: sentimentCategories,
format_instructions: parser.getFormatInstructions(),
}),
inputPrompt,
];

const prompt = ChatPromptTemplate.fromMessages(messages);
const chain = prompt.pipe(llm).pipe(parser).withConfig(getTracingConfig(this));

const output = await chain.invoke(messages);
burivuhster marked this conversation as resolved.
Show resolved Hide resolved
const sentimentIndex = categories.findIndex(
(s) => s.toLowerCase() === output.sentiment.toLowerCase(),
);

if (sentimentIndex !== -1) {
burivuhster marked this conversation as resolved.
Show resolved Hide resolved
const resultItem = { ...items[itemIdx] };
const sentimentAnalysis: IDataObject = {
category: output.sentiment,
};
if (options.includeDetailedResults) {
sentimentAnalysis.strength = output.strength;
sentimentAnalysis.confidence = output.confidence;
}
resultItem.json = {
...resultItem.json,
sentimentAnalysis,
};
returnData[sentimentIndex].push(resultItem);
}
}
return returnData;
}
}
1 change: 1 addition & 0 deletions packages/@n8n/nodes-langchain/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,7 @@
"dist/nodes/chains/ChainSummarization/ChainSummarization.node.js",
"dist/nodes/chains/ChainLLM/ChainLlm.node.js",
"dist/nodes/chains/ChainRetrievalQA/ChainRetrievalQa.node.js",
"dist/nodes/chains/SentimentAnalysis/SentimentAnalysis.node.js",
"dist/nodes/chains/TextClassifier/TextClassifier.node.js",
"dist/nodes/code/Code.node.js",
"dist/nodes/document_loaders/DocumentDefaultDataLoader/DocumentDefaultDataLoader.node.js",
Expand Down
2 changes: 2 additions & 0 deletions packages/editor-ui/src/plugins/icons/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ import {
faArrowDown,
faAt,
faBan,
faBalanceScaleLeft,
faBars,
faBolt,
faBook,
Expand Down Expand Up @@ -181,6 +182,7 @@ export const FontAwesomePlugin: Plugin = {
addIcon(faArrowDown);
addIcon(faAt);
addIcon(faBan);
addIcon(faBalanceScaleLeft);
addIcon(faBars);
addIcon(faBolt);
addIcon(faBook);
Expand Down