UNPKG

@n8n/n8n-nodes-langchain

Version:
238 lines • 12 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.LmChatAzureOpenAi = void 0; const anthropic_1 = require("@langchain/anthropic"); const openai_1 = require("@langchain/openai"); const ai_utilities_1 = require("@n8n/ai-utilities"); const n8n_workflow_1 = require("n8n-workflow"); const extra_body_1 = require("../shared/extra-body"); const api_key_1 = require("./credentials/api-key"); const error_handling_1 = require("./error-handling"); const oauth2_1 = require("./credentials/oauth2"); const searchModels_1 = require("./methods/searchModels"); const properties_1 = require("./properties"); class LmChatAzureOpenAi { constructor() { this.methods = { listSearch: { searchModels: searchModels_1.searchModels, }, }; this.description = { displayName: 'Microsoft Foundry Chat Model', name: 'lmChatAzureOpenAi', icon: 'file:foundry.svg', group: ['transform'], version: [1, 1.1], defaultVersion: 1.1, description: 'For advanced usage with an AI chain', defaults: { name: 'Microsoft Foundry Chat Model', }, codex: { categories: ['AI'], subcategories: { AI: ['Language Models', 'Root Nodes'], 'Language Models': ['Chat Models (Recommended)'], }, resources: { primaryDocumentation: [ { url: 'https://docs.n8n.io/integrations/builtin/cluster-nodes/sub-nodes/n8n-nodes-langchain.lmchatazureopenai/', }, ], }, alias: [ 'Azure', 'Azure OpenAI', 'Azure OpenAI Chat Model', 'Azure AI Foundry', 'Foundry', 'AOAI', ], }, inputs: [], outputs: [n8n_workflow_1.NodeConnectionTypes.AiLanguageModel], outputNames: ['Model'], credentials: [ { name: 'azureOpenAiApi', required: true, displayOptions: { show: { authentication: ["azureOpenAiApi"], }, }, }, { name: 'azureEntraCognitiveServicesOAuth2Api', required: true, displayOptions: { show: { authentication: ["azureEntraCognitiveServicesOAuth2Api"], }, }, }, ], properties: properties_1.properties, }; } async supplyData(itemIndex) { try { const authenticationMethod = this.getNodeParameter('authentication', itemIndex); const modelName = this.getNodeParameter('model', itemIndex, '', { extractValue: true, }); const allOptions = this.getNodeParameter('options', itemIndex, {}); const { extraBody, ...options } = allOptions; const extraBodyKwargs = extraBody ? (0, extra_body_1.parseExtraBody)(this, extraBody, itemIndex) : {}; const modelFamily = this.getNodeParameter('modelFamily', itemIndex, 'openai'); const responsesApiEnabled = this.getNodeParameter('responsesApiEnabled', itemIndex, false); const responseFormat = options.responseFormat ? responsesApiEnabled ? { text: { format: { type: options.responseFormat } } } : { response_format: { type: options.responseFormat } } : {}; const modelKwargs = { ...responseFormat, ...extraBodyKwargs, }; const hasModelKwargs = Object.keys(modelKwargs).length > 0; let modelConfig; switch (authenticationMethod) { case "azureOpenAiApi": modelConfig = await api_key_1.setupApiKeyAuthentication.call(this, 'azureOpenAiApi'); break; case "azureEntraCognitiveServicesOAuth2Api": modelConfig = await oauth2_1.setupOAuth2Authentication.call(this, 'azureEntraCognitiveServicesOAuth2Api'); break; default: throw new n8n_workflow_1.NodeOperationError(this.getNode(), 'Invalid authentication method'); } const timeout = options.timeout; if (modelFamily === 'anthropic') { if (!modelConfig.azureFoundryBaseURL) { throw new n8n_workflow_1.NodeOperationError(this.getNode(), 'Claude deployments need a credential using the Microsoft Foundry endpoint type', { itemIndex, description: 'This credential uses the classic endpoint type, which serves only the Azure OpenAI route. Switch the credential to Microsoft Foundry, or set Model Family to OpenAI.', }); } const anthropicURL = new URL(modelConfig.azureFoundryBaseURL).origin + '/anthropic'; const clientOptions = { fetch: ai_utilities_1.aiClientFetch, fetchOptions: { dispatcher: (0, ai_utilities_1.getProxyAgent)(anthropicURL, { headersTimeout: timeout, bodyTimeout: timeout }, this.helpers.getSecureEgressFilter()), }, timeout, authToken: null, }; if (modelConfig.azureADTokenProvider) { const getToken = modelConfig.azureADTokenProvider; const fetchWithEntraToken = async (input, init) => { const headers = new Headers(init?.headers); headers.set('Authorization', `Bearer ${await getToken()}`); headers.delete('x-api-key'); return await (0, ai_utilities_1.aiClientFetch)(input, { ...init, headers }); }; clientOptions.fetch = fetchWithEntraToken; } const model = new anthropic_1.ChatAnthropic({ model: modelName, anthropicApiKey: modelConfig.azureOpenAIApiKey ?? 'entra-id', anthropicApiUrl: anthropicURL, clientOptions, temperature: options.temperature, topP: options.topP, maxTokens: options.maxTokens && options.maxTokens > 0 ? options.maxTokens : undefined, maxRetries: options.maxRetries ?? 2, invocationKwargs: extraBodyKwargs, callbacks: [ new ai_utilities_1.N8nLlmTracing(this, { tokensUsageParser: ai_utilities_1.anthropicTokensUsageParser, genAiProviderName: 'anthropic', }), ], onFailedAttempt: (0, ai_utilities_1.makeN8nLlmFailedAttemptHandler)(this, (0, error_handling_1.makeAzureFoundryFailedAttemptHandler)(modelName, false, 'anthropic')), }); this.logger.info(`Microsoft Foundry (Anthropic) client initialized for model: ${modelName}`); return { response: model }; } if (modelConfig.azureFoundryBaseURL) { const foundryURL = modelConfig.azureFoundryBaseURL; const configuration = { baseURL: foundryURL, fetch: ai_utilities_1.aiClientFetch, fetchOptions: { dispatcher: (0, ai_utilities_1.getProxyAgent)(foundryURL, { headersTimeout: timeout, bodyTimeout: timeout, }, this.helpers.getSecureEgressFilter()), }, }; if (modelConfig.azureADTokenProvider) { configuration.apiKey = modelConfig.azureADTokenProvider; } const model = new openai_1.ChatOpenAI({ model: modelName, ...(modelConfig.azureOpenAIApiKey ? { apiKey: modelConfig.azureOpenAIApiKey } : {}), ...options, timeout, maxRetries: options.maxRetries ?? 2, configuration, callbacks: [new ai_utilities_1.N8nLlmTracing(this)], useResponsesApi: responsesApiEnabled, metadata: { output_format: responsesApiEnabled && options.responseFormat === 'json_object' ? 'json' : undefined, }, modelKwargs: hasModelKwargs ? modelKwargs : undefined, onFailedAttempt: (0, ai_utilities_1.makeN8nLlmFailedAttemptHandler)(this, (0, error_handling_1.makeAzureFoundryFailedAttemptHandler)(modelName, responsesApiEnabled)), }); this.logger.info(`Azure OpenAI (Foundry) client initialized for model: ${modelName}`); return { response: model }; } if (responsesApiEnabled) { throw new n8n_workflow_1.NodeOperationError(this.getNode(), 'The Responses API needs a credential using the Microsoft Foundry endpoint type', { itemIndex, description: "This credential uses the classic endpoint type, which addresses a deployment directly and has no Responses API. Switch the credential to Microsoft Foundry, or turn off 'Use Responses API'.", }); } const azureOpenAIEndpoint = modelConfig.azureOpenAIEndpoint || `https://${modelConfig.azureOpenAIApiInstanceName}.openai.azure.com`; const model = new openai_1.AzureChatOpenAI({ useResponsesApi: false, model: modelName, azureOpenAIApiDeploymentName: modelName, ...modelConfig, ...options, azureOpenAIEndpoint, timeout, maxRetries: options.maxRetries ?? 2, callbacks: [new ai_utilities_1.N8nLlmTracing(this)], configuration: { fetch: ai_utilities_1.aiClientFetch, fetchOptions: { dispatcher: (0, ai_utilities_1.getProxyAgent)(azureOpenAIEndpoint, { headersTimeout: timeout, bodyTimeout: timeout, }, this.helpers.getSecureEgressFilter()), }, }, modelKwargs: hasModelKwargs ? modelKwargs : undefined, onFailedAttempt: (0, ai_utilities_1.makeN8nLlmFailedAttemptHandler)(this, (0, error_handling_1.makeAzureFoundryFailedAttemptHandler)(modelName, false, 'classic')), }); this.logger.info(`Azure OpenAI client initialized for deployment: ${modelName}`); return { response: model, }; } catch (error) { this.logger.error(`Error in LmChatAzureOpenAi.supplyData: ${error.message}`, error); if (error instanceof n8n_workflow_1.NodeOperationError) { throw error; } throw new n8n_workflow_1.NodeOperationError(this.getNode(), `Failed to initialize the chat model client: ${error.message}`, error); } } } exports.LmChatAzureOpenAi = LmChatAzureOpenAi; //# sourceMappingURL=LmChatAzureOpenAi.node.js.map