|
1 | 1 | import { Service } from 'typedi';
|
2 | 2 | import config from '@/config';
|
3 | 3 | import type { INodeType, N8nAIProviderType, NodeError } from 'n8n-workflow';
|
4 |
| -import { createDebugErrorPrompt } from '@/services/ai/prompts/debugError'; |
| 4 | +import { ApplicationError, jsonParse } from 'n8n-workflow'; |
| 5 | +import { debugErrorPromptTemplate } from '@/services/ai/prompts/debugError'; |
5 | 6 | import type { BaseMessageLike } from '@langchain/core/messages';
|
6 | 7 | import { AIProviderOpenAI } from '@/services/ai/providers/openai';
|
7 |
| -import { AIProviderUnknown } from '@/services/ai/providers/unknown'; |
| 8 | +import type { BaseChatModelCallOptions } from '@langchain/core/language_models/chat_models'; |
| 9 | +import { summarizeNodeTypeProperties } from '@/services/ai/utils/summarizeNodeTypeProperties'; |
| 10 | +import { Pinecone } from '@pinecone-database/pinecone'; |
| 11 | +import type { z } from 'zod'; |
| 12 | +import apiKnowledgebase from '@/services/ai/resources/api-knowledgebase.json'; |
| 13 | +import { JsonOutputFunctionsParser } from 'langchain/output_parsers'; |
| 14 | +import { |
| 15 | + generateCurlCommandFallbackPromptTemplate, |
| 16 | + generateCurlCommandPromptTemplate, |
| 17 | +} from '@/services/ai/prompts/generateCurl'; |
| 18 | +import { generateCurlSchema } from '@/services/ai/schemas/generateCurl'; |
| 19 | +import { PineconeStore } from '@langchain/pinecone'; |
| 20 | +import Fuse from 'fuse.js'; |
| 21 | +import { N8N_DOCS_URL } from '@/constants'; |
| 22 | + |
| 23 | +interface APIKnowledgebaseService { |
| 24 | + id: string; |
| 25 | + title: string; |
| 26 | + description?: string; |
| 27 | +} |
8 | 28 |
|
9 | 29 | function isN8nAIProviderType(value: string): value is N8nAIProviderType {
|
10 | 30 | return ['openai'].includes(value);
|
11 | 31 | }
|
12 | 32 |
|
13 | 33 | @Service()
|
14 | 34 | export class AIService {
|
15 |
| - private provider: N8nAIProviderType = 'unknown'; |
| 35 | + private providerType: N8nAIProviderType = 'unknown'; |
| 36 | + |
| 37 | + public provider: AIProviderOpenAI; |
16 | 38 |
|
17 |
| - public model: AIProviderOpenAI | AIProviderUnknown = new AIProviderUnknown(); |
| 39 | + public pinecone: Pinecone; |
| 40 | + |
| 41 | + private jsonOutputParser = new JsonOutputFunctionsParser(); |
18 | 42 |
|
19 | 43 | constructor() {
|
20 | 44 | const providerName = config.getEnv('ai.provider');
|
| 45 | + |
21 | 46 | if (isN8nAIProviderType(providerName)) {
|
22 |
| - this.provider = providerName; |
| 47 | + this.providerType = providerName; |
23 | 48 | }
|
24 | 49 |
|
25 |
| - if (this.provider === 'openai') { |
26 |
| - const apiKey = config.getEnv('ai.openAIApiKey'); |
27 |
| - if (apiKey) { |
28 |
| - this.model = new AIProviderOpenAI({ apiKey }); |
| 50 | + if (this.providerType === 'openai') { |
| 51 | + const openAIApiKey = config.getEnv('ai.openAI.apiKey'); |
| 52 | + const openAIModelName = config.getEnv('ai.openAI.model'); |
| 53 | + |
| 54 | + if (openAIApiKey) { |
| 55 | + this.provider = new AIProviderOpenAI({ openAIApiKey, modelName: openAIModelName }); |
29 | 56 | }
|
30 | 57 | }
|
| 58 | + |
| 59 | + const pineconeApiKey = config.getEnv('ai.pinecone.apiKey'); |
| 60 | + if (pineconeApiKey) { |
| 61 | + this.pinecone = new Pinecone({ |
| 62 | + apiKey: pineconeApiKey, |
| 63 | + }); |
| 64 | + } |
31 | 65 | }
|
32 | 66 |
|
33 |
| - async prompt(messages: BaseMessageLike[]) { |
34 |
| - return await this.model.prompt(messages); |
| 67 | + async prompt(messages: BaseMessageLike[], options?: BaseChatModelCallOptions) { |
| 68 | + if (!this.provider) { |
| 69 | + throw new ApplicationError('No AI provider has been configured.'); |
| 70 | + } |
| 71 | + |
| 72 | + return await this.provider.invoke(messages, options); |
35 | 73 | }
|
36 | 74 |
|
37 | 75 | async debugError(error: NodeError, nodeType?: INodeType) {
|
38 |
| - return await this.prompt(createDebugErrorPrompt(error, nodeType)); |
| 76 | + this.checkRequirements(); |
| 77 | + |
| 78 | + const chain = debugErrorPromptTemplate.pipe(this.provider.model); |
| 79 | + const result = await chain.invoke({ |
| 80 | + nodeType: nodeType?.description.displayName ?? 'n8n Node', |
| 81 | + error: JSON.stringify(error), |
| 82 | + properties: JSON.stringify( |
| 83 | + summarizeNodeTypeProperties(nodeType?.description.properties ?? []), |
| 84 | + ), |
| 85 | + documentationUrl: nodeType?.description.documentationUrl ?? N8N_DOCS_URL, |
| 86 | + }); |
| 87 | + |
| 88 | + return this.provider.mapResponse(result); |
| 89 | + } |
| 90 | + |
| 91 | + validateCurl(result: { curl: string }) { |
| 92 | + if (!result.curl.startsWith('curl')) { |
| 93 | + throw new ApplicationError( |
| 94 | + 'The generated HTTP Request Node parameters format is incorrect. Please adjust your request and try again.', |
| 95 | + ); |
| 96 | + } |
| 97 | + |
| 98 | + result.curl = result.curl |
| 99 | + /* |
| 100 | + * Replaces placeholders like `{VALUE}` or `{{VALUE}}` with quoted placeholders `"{VALUE}"` or `"{{VALUE}}"`, |
| 101 | + * ensuring that the placeholders are properly formatted within the curl command. |
| 102 | + * - ": a colon followed by a double quote and a space |
| 103 | + * - ( starts a capturing group |
| 104 | + * - \{\{ two opening curly braces |
| 105 | + * - [A-Za-z0-9_]+ one or more alphanumeric characters or underscores |
| 106 | + * - }} two closing curly braces |
| 107 | + * - | OR |
| 108 | + * - \{ an opening curly brace |
| 109 | + * - [A-Za-z0-9_]+ one or more alphanumeric characters or underscores |
| 110 | + * - } a closing curly brace |
| 111 | + * - ) ends the capturing group |
| 112 | + * - /g performs a global search and replace |
| 113 | + * |
| 114 | + */ |
| 115 | + .replace(/": (\{\{[A-Za-z0-9_]+}}|\{[A-Za-z0-9_]+})/g, '": "$1"') // Fix for placeholders `curl -d '{ "key": {VALUE} }'` |
| 116 | + /* |
| 117 | + * Removes the rogue curly bracket at the end of the curl command if it is present. |
| 118 | + * It ensures that the curl command is properly formatted and doesn't have an extra closing curly bracket. |
| 119 | + * - ( starts a capturing group |
| 120 | + * - -d flag in the curl command |
| 121 | + * - ' a single quote |
| 122 | + * - [^']+ one or more characters that are not a single quote |
| 123 | + * - ' a single quote |
| 124 | + * - ) ends the capturing group |
| 125 | + * - } a closing curly bracket |
| 126 | + */ |
| 127 | + .replace(/(-d '[^']+')}/, '$1'); // Fix for rogue curly bracket `curl -d '{ "key": "value" }'}` |
| 128 | + |
| 129 | + return result; |
| 130 | + } |
| 131 | + |
| 132 | + async generateCurl(serviceName: string, serviceRequest: string) { |
| 133 | + this.checkRequirements(); |
| 134 | + |
| 135 | + if (!this.pinecone) { |
| 136 | + return await this.generateCurlGeneric(serviceName, serviceRequest); |
| 137 | + } |
| 138 | + |
| 139 | + const fuse = new Fuse(apiKnowledgebase as unknown as APIKnowledgebaseService[], { |
| 140 | + threshold: 0.25, |
| 141 | + useExtendedSearch: true, |
| 142 | + keys: ['id', 'title'], |
| 143 | + }); |
| 144 | + |
| 145 | + const matchedServices = fuse |
| 146 | + .search(serviceName.replace(/ +/g, '|')) |
| 147 | + .map((result) => result.item); |
| 148 | + |
| 149 | + if (matchedServices.length === 0) { |
| 150 | + return await this.generateCurlGeneric(serviceName, serviceRequest); |
| 151 | + } |
| 152 | + |
| 153 | + const pcIndex = this.pinecone.Index('api-knowledgebase'); |
| 154 | + const vectorStore = await PineconeStore.fromExistingIndex(this.provider.embeddings, { |
| 155 | + namespace: 'endpoints', |
| 156 | + pineconeIndex: pcIndex, |
| 157 | + }); |
| 158 | + |
| 159 | + const matchedDocuments = await vectorStore.similaritySearch( |
| 160 | + `${serviceName} ${serviceRequest}`, |
| 161 | + 4, |
| 162 | + { |
| 163 | + id: { |
| 164 | + $in: matchedServices.map((service) => service.id), |
| 165 | + }, |
| 166 | + }, |
| 167 | + ); |
| 168 | + |
| 169 | + if (matchedDocuments.length === 0) { |
| 170 | + return await this.generateCurlGeneric(serviceName, serviceRequest); |
| 171 | + } |
| 172 | + |
| 173 | + const aggregatedDocuments = matchedDocuments.reduce<unknown[]>((acc, document) => { |
| 174 | + const pageData = jsonParse(document.pageContent); |
| 175 | + |
| 176 | + acc.push(pageData); |
| 177 | + |
| 178 | + return acc; |
| 179 | + }, []); |
| 180 | + |
| 181 | + const generateCurlChain = generateCurlCommandPromptTemplate |
| 182 | + .pipe(this.provider.modelWithOutputParser(generateCurlSchema)) |
| 183 | + .pipe(this.jsonOutputParser); |
| 184 | + const result = (await generateCurlChain.invoke({ |
| 185 | + endpoints: JSON.stringify(aggregatedDocuments), |
| 186 | + serviceName, |
| 187 | + serviceRequest, |
| 188 | + })) as z.infer<typeof generateCurlSchema>; |
| 189 | + |
| 190 | + return this.validateCurl(result); |
| 191 | + } |
| 192 | + |
| 193 | + async generateCurlGeneric(serviceName: string, serviceRequest: string) { |
| 194 | + this.checkRequirements(); |
| 195 | + |
| 196 | + const generateCurlFallbackChain = generateCurlCommandFallbackPromptTemplate |
| 197 | + .pipe(this.provider.modelWithOutputParser(generateCurlSchema)) |
| 198 | + .pipe(this.jsonOutputParser); |
| 199 | + const result = (await generateCurlFallbackChain.invoke({ |
| 200 | + serviceName, |
| 201 | + serviceRequest, |
| 202 | + })) as z.infer<typeof generateCurlSchema>; |
| 203 | + |
| 204 | + return this.validateCurl(result); |
| 205 | + } |
| 206 | + |
| 207 | + checkRequirements() { |
| 208 | + if (!this.provider) { |
| 209 | + throw new ApplicationError('No AI provider has been configured.'); |
| 210 | + } |
39 | 211 | }
|
40 | 212 | }
|
0 commit comments