-
Notifications
You must be signed in to change notification settings - Fork 57.3k
Expand file tree
/
Copy pathToolCode.node.ts
More file actions
345 lines (314 loc) · 9.47 KB
/
ToolCode.node.ts
File metadata and controls
345 lines (314 loc) · 9.47 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
import { DynamicStructuredTool, DynamicTool } from '@langchain/core/tools';
import type { JSONSchema7 } from 'json-schema';
import { JsTaskRunnerSandbox } from 'n8n-nodes-base/dist/nodes/Code/JsTaskRunnerSandbox';
import { PythonTaskRunnerSandbox } from 'n8n-nodes-base/dist/nodes/Code/PythonTaskRunnerSandbox';
import type {
ExecutionError,
IDataObject,
IExecuteFunctions,
INodeExecutionData,
INodeType,
INodeTypeDescription,
ISupplyDataFunctions,
SupplyData,
} from 'n8n-workflow';
import {
jsonParse,
NodeConnectionTypes,
nodeNameToToolName,
NodeOperationError,
} from 'n8n-workflow';
import {
buildInputSchemaField,
buildJsonSchemaExampleField,
buildJsonSchemaExampleNotice,
schemaTypeField,
} from '@utils/descriptions';
import { convertJsonSchemaToZod, generateSchemaFromExample } from '@utils/schemaParsing';
import { getConnectionHintNoticeField, logAiEvent } from '@n8n/ai-utilities';
import type { DynamicZodObject } from '../../../types/zod.types';
const jsonSchemaExampleField = buildJsonSchemaExampleField({
showExtraProps: { specifyInputSchema: [true] },
});
const jsonSchemaExampleNotice = buildJsonSchemaExampleNotice({
showExtraProps: {
specifyInputSchema: [true],
'@version': [{ _cnd: { gte: 1.3 } }],
},
});
const jsonSchemaField = buildInputSchemaField({ showExtraProps: { specifyInputSchema: [true] } });
function getTool(
ctx: ISupplyDataFunctions | IExecuteFunctions,
itemIndex: number,
log: boolean = true,
) {
const node = ctx.getNode();
const workflowMode = ctx.getMode();
const { typeVersion } = node;
const name =
typeVersion <= 1.1
? (ctx.getNodeParameter('name', itemIndex) as string)
: nodeNameToToolName(node);
const description = ctx.getNodeParameter('description', itemIndex) as string;
const useSchema = ctx.getNodeParameter('specifyInputSchema', itemIndex) as boolean;
const language = ctx.getNodeParameter('language', itemIndex) as string;
let code = '';
if (language === 'javaScript') {
code = ctx.getNodeParameter('jsCode', itemIndex) as string;
} else {
code = ctx.getNodeParameter('pythonCode', itemIndex) as string;
}
const runFunction = async (query: string | IDataObject): Promise<unknown> => {
if (language === 'javaScript') {
const sandbox = new JsTaskRunnerSandbox(workflowMode, ctx, /*chunkSize=*/ undefined, {
query,
});
return await sandbox.runCodeForTool(code);
} else {
const sandbox = new PythonTaskRunnerSandbox(
code,
'runOnceForAllItems',
workflowMode,
ctx as IExecuteFunctions,
{
query,
},
);
return await sandbox.runCodeForTool();
}
};
const toolHandler = async (query: string | IDataObject): Promise<string> => {
const { index } = log
? ctx.addInputData(NodeConnectionTypes.AiTool, [[{ json: { query } }]])
: { index: 0 };
let response: any = '';
let executionError: ExecutionError | undefined;
try {
response = await runFunction(query);
} catch (error: unknown) {
executionError = new NodeOperationError(ctx.getNode(), error as ExecutionError);
response = `There was an error: "${executionError.message}"`;
}
if (typeof response === 'number') {
response = (response as number).toString();
}
if (typeof response !== 'string') {
// TODO: Do some more testing. Issues here should actually fail the workflow
executionError = new NodeOperationError(ctx.getNode(), 'Wrong output type returned', {
description: `The response property should be a string, but it is an ${typeof response}`,
});
response = `There was an error: "${executionError.message}"`;
}
if (executionError && log) {
void ctx.addOutputData(NodeConnectionTypes.AiTool, index, executionError);
} else if (log) {
void ctx.addOutputData(NodeConnectionTypes.AiTool, index, [[{ json: { response } }]]);
logAiEvent(ctx, 'ai-tool-called', { query, response });
}
return response;
};
const commonToolOptions = {
name,
description,
func: toolHandler,
};
let tool: DynamicTool | DynamicStructuredTool | undefined = undefined;
if (useSchema) {
try {
// We initialize these even though one of them will always be empty
// it makes it easier to navigate the ternary operator
const jsonExample = ctx.getNodeParameter('jsonSchemaExample', itemIndex, '') as string;
const inputSchema = ctx.getNodeParameter('inputSchema', itemIndex, '') as string;
const schemaType = ctx.getNodeParameter('schemaType', itemIndex) as 'fromJson' | 'manual';
const jsonSchema =
schemaType === 'fromJson'
? generateSchemaFromExample(jsonExample, ctx.getNode().typeVersion >= 1.3)
: jsonParse<JSONSchema7>(inputSchema);
const zodSchema = convertJsonSchemaToZod<DynamicZodObject>(jsonSchema);
tool = new DynamicStructuredTool({
schema: zodSchema,
...commonToolOptions,
});
} catch (error) {
throw new NodeOperationError(
ctx.getNode(),
'Error during parsing of JSON Schema. \n ' + error,
);
}
} else {
tool = new DynamicTool(commonToolOptions);
}
return tool;
}
export class ToolCode implements INodeType {
description: INodeTypeDescription = {
displayName: 'Code Tool',
name: 'toolCode',
icon: 'fa:code',
iconColor: 'black',
group: ['transform'],
version: [1, 1.1, 1.2, 1.3],
description: 'Write a tool in JS or Python',
defaults: {
name: 'Code Tool',
},
codex: {
categories: ['AI'],
subcategories: {
AI: ['Tools'],
Tools: ['Recommended Tools'],
},
resources: {
primaryDocumentation: [
{
url: 'https://docs.n8n.io/integrations/builtin/cluster-nodes/sub-nodes/n8n-nodes-langchain.toolcode/',
},
],
},
},
inputs: [],
outputs: [NodeConnectionTypes.AiTool],
outputNames: ['Tool'],
properties: [
getConnectionHintNoticeField([NodeConnectionTypes.AiAgent]),
{
displayName:
'See an example of a conversational agent with custom tool written in JavaScript <a href="/templates/1963" target="_blank">here</a>.',
name: 'noticeTemplateExample',
type: 'notice',
default: '',
},
{
displayName: 'Name',
name: 'name',
type: 'string',
default: '',
placeholder: 'My_Tool',
displayOptions: {
show: {
'@version': [1],
},
},
},
{
displayName: 'Name',
name: 'name',
type: 'string',
default: '',
placeholder: 'e.g. My_Tool',
validateType: 'string-alphanumeric',
description:
'The name of the function to be called, could contain letters, numbers, and underscores only',
displayOptions: {
show: {
'@version': [1.1],
},
},
},
{
displayName: 'Description',
name: 'description',
type: 'string',
default: '',
placeholder:
'Call this tool to get a random color. The input should be a string with comma separted names of colors to exclude.',
typeOptions: {
rows: 3,
},
},
{
displayName: 'Language',
name: 'language',
type: 'options',
noDataExpression: true,
options: [
{
name: 'JavaScript',
value: 'javaScript',
},
{
name: 'Python (Beta)',
value: 'python',
},
],
default: 'javaScript',
},
{
displayName: 'JavaScript',
name: 'jsCode',
type: 'string',
displayOptions: {
show: {
language: ['javaScript'],
},
},
typeOptions: {
editor: 'jsEditor',
},
default:
'// Example: convert the incoming query to uppercase and return it\nreturn query.toUpperCase()',
// TODO: Add proper text here later
hint: 'You can access the input the tool receives via the input property "query". The returned value should be a single string.',
// eslint-disable-next-line n8n-nodes-base/node-param-description-missing-final-period
description: 'E.g. Converts any text to uppercase',
noDataExpression: true,
},
{
displayName: 'Python',
name: 'pythonCode',
type: 'string',
displayOptions: {
show: {
language: ['python'],
},
},
typeOptions: {
editor: 'codeNodeEditor', // TODO: create a separate `pythonEditor` component
editorLanguage: 'python',
},
default:
'# Example: convert the incoming query to uppercase and return it\nreturn _query.upper()',
// TODO: Add proper text here later
hint: 'You can access the input the tool receives via the input property "_query". The returned value should be a single string.',
// eslint-disable-next-line n8n-nodes-base/node-param-description-missing-final-period
description: 'E.g. Converts any text to uppercase',
noDataExpression: true,
},
{
displayName: 'Specify Input Schema',
name: 'specifyInputSchema',
type: 'boolean',
description:
'Whether to specify the schema for the function. This would require the LLM to provide the input in the correct format and would validate it against the schema.',
noDataExpression: true,
default: false,
},
{ ...schemaTypeField, displayOptions: { show: { specifyInputSchema: [true] } } },
jsonSchemaExampleField,
jsonSchemaExampleNotice,
jsonSchemaField,
],
};
async supplyData(this: ISupplyDataFunctions, itemIndex: number): Promise<SupplyData> {
return {
response: getTool(this, itemIndex),
};
}
async execute(this: IExecuteFunctions): Promise<INodeExecutionData[][]> {
const result: INodeExecutionData[] = [];
const input = this.getInputData();
for (let i = 0; i < input.length; i++) {
const item = input[i];
const tool = getTool(this, i, false);
result.push({
json: {
response: await tool.invoke(item.json),
},
pairedItem: {
item: i,
},
});
}
return [result];
}
}