UNPKG

@n8n/n8n-nodes-langchain

Version:

![Banner image](https://user-images.githubusercontent.com/10284570/173569848-c624317f-42b1-45a6-ab09-f0ea3c247648.png)

211 lines (210 loc) 8.59 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.OutputParserStructured = void 0; const prompts_1 = require("@langchain/core/prompts"); const n8n_workflow_1 = require("n8n-workflow"); const descriptions_1 = require("../../../utils/descriptions"); const N8nOutputParser_1 = require("../../../utils/output_parsers/N8nOutputParser"); const schemaParsing_1 = require("../../../utils/schemaParsing"); const ai_utilities_1 = require("@n8n/ai-utilities"); const prompt_1 = require("./prompt"); class OutputParserStructured { constructor() { this.description = { displayName: 'Structured Output Parser', name: 'outputParserStructured', icon: 'node:structured-output-parser', iconColor: 'black', group: ['transform'], version: [1, 1.1, 1.2, 1.3], defaultVersion: 1.3, description: 'Return data in a defined JSON format', defaults: { name: 'Structured Output Parser', }, codex: { alias: ['json', 'zod'], categories: ['AI'], subcategories: { AI: ['Output Parsers'], }, resources: { primaryDocumentation: [ { url: 'https://docs.n8n.io/integrations/builtin/cluster-nodes/sub-nodes/n8n-nodes-langchain.outputparserstructured/', }, ], }, }, inputs: `={{ ((parameters) => { if (parameters?.autoFix) { return [ { displayName: 'Model', maxConnections: 1, type: "${n8n_workflow_1.NodeConnectionTypes.AiLanguageModel}", required: true } ]; } return []; })($parameter) }}`, outputs: [n8n_workflow_1.NodeConnectionTypes.AiOutputParser], outputNames: ['Output Parser'], properties: [ (0, ai_utilities_1.getConnectionHintNoticeField)([n8n_workflow_1.NodeConnectionTypes.AiChain, n8n_workflow_1.NodeConnectionTypes.AiAgent]), { ...descriptions_1.schemaTypeField, displayOptions: { show: { '@version': [{ _cnd: { gte: 1.2 } }] } } }, { ...descriptions_1.jsonSchemaExampleField, default: `{ "state": "California", "cities": ["Los Angeles", "San Francisco", "San Diego"] }`, }, (0, descriptions_1.buildJsonSchemaExampleNotice)({ showExtraProps: { '@version': [{ _cnd: { gte: 1.3 } }], }, }), { ...descriptions_1.inputSchemaField, default: `{ "type": "object", "properties": { "state": { "type": "string" }, "cities": { "type": "array", "items": { "type": "string" } } } }`, }, { displayName: 'JSON Schema', name: 'jsonSchema', type: 'json', description: 'JSON Schema to structure and validate the output against', default: `{ "type": "object", "properties": { "state": { "type": "string" }, "cities": { "type": "array", "items": { "type": "string" } } } }`, typeOptions: { rows: 10, }, required: true, displayOptions: { show: { '@version': [{ _cnd: { lte: 1.1 } }], }, }, }, { displayName: 'Auto-Fix Format', description: 'Whether to automatically fix the output when it is not in the correct format. Will cause another LLM call.', name: 'autoFix', type: 'boolean', default: false, }, { displayName: 'Customize Retry Prompt', name: 'customizeRetryPrompt', type: 'boolean', displayOptions: { show: { autoFix: [true], }, }, default: false, description: 'Whether to customize the prompt used for retrying the output parsing. If disabled, a default prompt will be used.', }, { displayName: 'Custom Prompt', name: 'prompt', type: 'string', displayOptions: { show: { autoFix: [true], customizeRetryPrompt: [true], }, }, default: prompt_1.NAIVE_FIX_PROMPT, typeOptions: { rows: 10, }, hint: 'Should include "{error}", "{instructions}", and "{completion}" placeholders', description: 'Prompt template used for fixing the output. Uses placeholders: "{instructions}" for parsing rules, "{completion}" for the failed attempt, and "{error}" for the validation error message.', }, ], hints: [ { message: 'Fields that use $refs might have the wrong type, since this syntax is not currently supported', type: 'warning', location: 'outputPane', whenToDisplay: 'afterExecution', displayCondition: '={{ $parameter["schemaType"] === "manual" && $parameter["inputSchema"]?.includes("$ref") }}', }, ], builderHint: { message: 'Output data is wrapped in an "output" key, e.g. { "output": { "state": "California", "cities": ["San Francisco"] } }', inputs: { ai_languageModel: { required: true, displayOptions: { show: { autoFix: [true] } }, }, }, }, }; } async supplyData(itemIndex) { const schemaType = this.getNodeParameter('schemaType', itemIndex, ''); const jsonExample = this.getNodeParameter('jsonSchemaExample', itemIndex, ''); let inputSchema; const jsonExampleAllFieldsRequired = this.getNode().typeVersion >= 1.3; if (this.getNode().typeVersion <= 1.1) { inputSchema = this.getNodeParameter('jsonSchema', itemIndex, ''); } else { inputSchema = this.getNodeParameter('inputSchema', itemIndex, ''); } const jsonSchema = schemaType === 'fromJson' ? (0, schemaParsing_1.generateSchemaFromExample)(jsonExample, jsonExampleAllFieldsRequired) : (0, n8n_workflow_1.jsonParse)(inputSchema); const zodSchema = (0, schemaParsing_1.convertJsonSchemaToZod)(jsonSchema); const nodeVersion = this.getNode().typeVersion; const autoFix = this.getNodeParameter('autoFix', itemIndex, false); let outputParser; try { outputParser = await N8nOutputParser_1.N8nStructuredOutputParser.fromZodJsonSchema(zodSchema, nodeVersion, this); } catch (error) { throw new n8n_workflow_1.NodeOperationError(this.getNode(), 'Error during parsing of JSON Schema. Please check the schema and try again.'); } if (!autoFix) { return { response: outputParser, }; } const model = (await this.getInputConnectionData(n8n_workflow_1.NodeConnectionTypes.AiLanguageModel, itemIndex)); const prompt = this.getNodeParameter('prompt', itemIndex, prompt_1.NAIVE_FIX_PROMPT); if (prompt.length === 0 || !prompt.includes('{error}')) { throw new n8n_workflow_1.NodeOperationError(this.getNode(), 'Auto-fixing parser prompt has to contain {error} placeholder'); } const parser = new N8nOutputParser_1.N8nOutputFixingParser(this, model, outputParser, prompts_1.PromptTemplate.fromTemplate(prompt)); return { response: parser, }; } } exports.OutputParserStructured = OutputParserStructured; //# sourceMappingURL=OutputParserStructured.node.js.map