Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
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
81 changes: 37 additions & 44 deletions packages/@n8n/nodes-langchain/nodes/Guardrails/Guardrails.node.ts
Original file line number Diff line number Diff line change
@@ -1,50 +1,43 @@
import type { IExecuteFunctions, INodeExecutionData, INodeType } from 'n8n-workflow';
import {
VersionedNodeType,
type INodeTypeBaseDescription,
type IVersionedNodeType,
} from 'n8n-workflow';

import { process } from './actions/process';
import { versionDescription } from './description';
import { getChatModel } from './helpers/model';
import { GuardrailsV1 } from './v1/GuardrailsV1.node';
import { GuardrailsV2 } from './v2/GuardrailsV2.node';

export class Guardrails implements INodeType {
description = versionDescription;
export class Guardrails extends VersionedNodeType {
constructor() {
const baseDescription: INodeTypeBaseDescription = {
displayName: 'Guardrails',
name: 'guardrails',
icon: 'file:guardrails.svg',
group: ['transform'],
defaultVersion: 2,
description:
'Safeguard AI models from malicious input or prevent them from generating undesirable responses',
codex: {
alias: ['LangChain', 'Guardrails', 'PII', 'Secret', 'Injection', 'Sanitize'],
categories: ['AI'],
subcategories: {
AI: ['Agents', 'Miscellaneous', 'Root Nodes'],
},
resources: {
primaryDocumentation: [
{
url: 'https://docs.n8n.io/integrations/builtin/core-nodes/n8n-nodes-langchain.guardrails/',
},
],
},
},
};

async execute(this: IExecuteFunctions): Promise<INodeExecutionData[][]> {
const items = this.getInputData();
const operation = this.getNodeParameter('operation', 0) as 'classify' | 'sanitize';
const model = operation === 'classify' ? await getChatModel.call(this) : null;
const nodeVersions: IVersionedNodeType['nodeVersions'] = {
1: new GuardrailsV1(baseDescription),
2: new GuardrailsV2(baseDescription),
};

const failedItems: INodeExecutionData[] = [];
const passedItems: INodeExecutionData[] = [];
for (let i = 0; i < items.length; i++) {
try {
const responseData = await process.call(this, i, model);
if (responseData.passed) {
passedItems.push({
json: { guardrailsInput: responseData.guardrailsInput, ...responseData.passed },
pairedItem: { item: i },
});
}
if (responseData.failed) {
failedItems.push({
json: { guardrailsInput: responseData.guardrailsInput, ...responseData.failed },
pairedItem: { item: i },
});
}
} catch (error) {
if (this.continueOnFail()) {
failedItems.push({
json: { error: error.message, guardrailsInput: '' },
pairedItem: { item: i },
});
} else {
throw error;
}
}
}

if (operation === 'classify') {
return [passedItems, failedItems];
}

return [passedItems];
super(nodeVersions, baseDescription);
}
}
49 changes: 49 additions & 0 deletions packages/@n8n/nodes-langchain/nodes/Guardrails/actions/execute.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
import type { IExecuteFunctions, INodeExecutionData } from 'n8n-workflow';

import { process } from './process';
import type { GuardrailsOptions } from './types';
import { hasLLMGuardrails } from '../helpers/configureNodeInputs';
import { getChatModel } from '../helpers/model';

export async function execute(this: IExecuteFunctions): Promise<INodeExecutionData[][]> {
const items = this.getInputData();
const operation = this.getNodeParameter('operation', 0) as 'classify' | 'sanitize';
const model = hasLLMGuardrails(this.getNodeParameter('guardrails', 0) as GuardrailsOptions)
? await getChatModel.call(this)
: null;

const failedItems: INodeExecutionData[] = [];
const passedItems: INodeExecutionData[] = [];
for (let i = 0; i < items.length; i++) {
try {
const responseData = await process.call(this, i, model);
if (responseData.passed) {
passedItems.push({
json: { guardrailsInput: responseData.guardrailsInput, ...responseData.passed },
pairedItem: { item: i },
});
}
if (responseData.failed) {
failedItems.push({
json: { guardrailsInput: responseData.guardrailsInput, ...responseData.failed },
pairedItem: { item: i },
});
}
} catch (error) {
if (this.continueOnFail()) {
failedItems.push({
json: { error: error.message, guardrailsInput: '' },
pairedItem: { item: i },
});
} else {
throw error;
}
}
}

if (operation === 'classify') {
return [passedItems, failedItems];
}

return [passedItems];
}
19 changes: 11 additions & 8 deletions packages/@n8n/nodes-langchain/nodes/Guardrails/actions/process.ts
Original file line number Diff line number Diff line change
Expand Up @@ -80,6 +80,13 @@ export async function process(
input: [],
};

const checkModelAvailable = (model: BaseChatModel | null): model is BaseChatModel => {
if (!model) {
throw new NodeOperationError(this.getNode(), 'Chat Model is required');
}
return true;
};

if (guardrails.pii?.value) {
const { entities } = guardrails.pii.value;
stageGuardrails.preflight.push({
Expand Down Expand Up @@ -121,18 +128,14 @@ export async function process(
}

if (operation === 'classify') {
if (!model) {
throw new NodeOperationError(this.getNode(), 'Chat Model is required for classify operation');
}

if (guardrails.keywords) {
stageGuardrails.input.push({
name: 'keywords',
check: createKeywordsCheckFn({ keywords: splitByComma(guardrails.keywords) }),
});
}

if (guardrails.jailbreak?.value) {
if (guardrails.jailbreak?.value && checkModelAvailable(model)) {
const { prompt, threshold } = guardrails.jailbreak.value;
stageGuardrails.input.push({
name: 'jailbreak',
Expand All @@ -145,7 +148,7 @@ export async function process(
});
}

if (guardrails.nsfw?.value) {
if (guardrails.nsfw?.value && checkModelAvailable(model)) {
const { prompt, threshold } = guardrails.nsfw.value;
stageGuardrails.input.push({
name: 'nsfw',
Expand All @@ -158,7 +161,7 @@ export async function process(
});
}

if (guardrails.topicalAlignment?.value) {
if (guardrails.topicalAlignment?.value && checkModelAvailable(model)) {
const { prompt, threshold } = guardrails.topicalAlignment.value;
stageGuardrails.input.push({
name: 'topicalAlignment',
Expand All @@ -171,7 +174,7 @@ export async function process(
});
}

if (guardrails.custom?.guardrail) {
if (guardrails.custom?.guardrail && checkModelAvailable(model)) {
for (const customGuardrail of guardrails.custom.guardrail) {
const { prompt, threshold, name } = customGuardrail;
stageGuardrails.input.push({
Expand Down
Loading
Loading