first commit
Security: Sync from Public / sync-from-public (push) Has been cancelled
Test: Benchmark Nightly / build (push) Has been cancelled
Test: Benchmark Nightly / Notify Cats on failure (push) Has been cancelled
CI: Python / Checks (push) Has been cancelled
Test: Evals Python / Workflow Comparison Python (push) Has been cancelled
Util: Check Docs URLs / check-docs-urls (push) Has been cancelled
Test: Visual Storybook / Cloudflare Pages (push) Has been cancelled
Test: E2E Performance / build-and-test-performance (push) Has been cancelled
Test: Workflows Nightly / Run Workflow Tests (push) Has been cancelled
Util: Cleanup CI Docker Images / Delete stale CI images (push) Has been cancelled
Test: Benchmark Destroy Env / build (push) Has been cancelled
Util: Update Node Popularity / update-popularity (push) Has been cancelled
Test: E2E Coverage Weekly / Coverage Tests (push) Has been cancelled
Security: Sync from Public / sync-from-public (push) Has been cancelled
Test: Benchmark Nightly / build (push) Has been cancelled
Test: Benchmark Nightly / Notify Cats on failure (push) Has been cancelled
CI: Python / Checks (push) Has been cancelled
Test: Evals Python / Workflow Comparison Python (push) Has been cancelled
Util: Check Docs URLs / check-docs-urls (push) Has been cancelled
Test: Visual Storybook / Cloudflare Pages (push) Has been cancelled
Test: E2E Performance / build-and-test-performance (push) Has been cancelled
Test: Workflows Nightly / Run Workflow Tests (push) Has been cancelled
Util: Cleanup CI Docker Images / Delete stale CI images (push) Has been cancelled
Test: Benchmark Destroy Env / build (push) Has been cancelled
Util: Update Node Popularity / update-popularity (push) Has been cancelled
Test: E2E Coverage Weekly / Coverage Tests (push) Has been cancelled
This commit is contained in:
@@ -0,0 +1,154 @@
|
||||
import { AzureChatOpenAI } from '@langchain/openai';
|
||||
import { getProxyAgent, makeN8nLlmFailedAttemptHandler, N8nLlmTracing } from '@n8n/ai-utilities';
|
||||
import {
|
||||
NodeOperationError,
|
||||
NodeConnectionTypes,
|
||||
type INodeType,
|
||||
type INodeTypeDescription,
|
||||
type ISupplyDataFunctions,
|
||||
type SupplyData,
|
||||
} from 'n8n-workflow';
|
||||
|
||||
import { setupApiKeyAuthentication } from './credentials/api-key';
|
||||
import { setupOAuth2Authentication } from './credentials/oauth2';
|
||||
import { properties } from './properties';
|
||||
import { AuthenticationType } from './types';
|
||||
import type {
|
||||
AzureOpenAIApiKeyModelConfig,
|
||||
AzureOpenAIOAuth2ModelConfig,
|
||||
AzureOpenAIOptions,
|
||||
} from './types';
|
||||
|
||||
export class LmChatAzureOpenAi implements INodeType {
|
||||
description: INodeTypeDescription = {
|
||||
displayName: 'Azure OpenAI Chat Model',
|
||||
|
||||
name: 'lmChatAzureOpenAi',
|
||||
icon: 'file:azure.svg',
|
||||
group: ['transform'],
|
||||
version: 1,
|
||||
description: 'For advanced usage with an AI chain',
|
||||
defaults: {
|
||||
name: 'Azure OpenAI 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/',
|
||||
},
|
||||
],
|
||||
},
|
||||
},
|
||||
|
||||
inputs: [],
|
||||
|
||||
outputs: [NodeConnectionTypes.AiLanguageModel],
|
||||
outputNames: ['Model'],
|
||||
credentials: [
|
||||
{
|
||||
name: 'azureOpenAiApi',
|
||||
required: true,
|
||||
displayOptions: {
|
||||
show: {
|
||||
authentication: [AuthenticationType.ApiKey],
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
name: 'azureEntraCognitiveServicesOAuth2Api',
|
||||
required: true,
|
||||
displayOptions: {
|
||||
show: {
|
||||
authentication: [AuthenticationType.EntraOAuth2],
|
||||
},
|
||||
},
|
||||
},
|
||||
],
|
||||
properties,
|
||||
};
|
||||
|
||||
async supplyData(this: ISupplyDataFunctions, itemIndex: number): Promise<SupplyData> {
|
||||
try {
|
||||
const authenticationMethod = this.getNodeParameter(
|
||||
'authentication',
|
||||
itemIndex,
|
||||
) as AuthenticationType;
|
||||
const modelName = this.getNodeParameter('model', itemIndex) as string;
|
||||
const options = this.getNodeParameter('options', itemIndex, {}) as AzureOpenAIOptions;
|
||||
|
||||
// Set up Authentication based on selection and get configuration
|
||||
let modelConfig: AzureOpenAIApiKeyModelConfig | AzureOpenAIOAuth2ModelConfig;
|
||||
switch (authenticationMethod) {
|
||||
case AuthenticationType.ApiKey:
|
||||
modelConfig = await setupApiKeyAuthentication.call(this, 'azureOpenAiApi');
|
||||
break;
|
||||
case AuthenticationType.EntraOAuth2:
|
||||
modelConfig = await setupOAuth2Authentication.call(
|
||||
this,
|
||||
'azureEntraCognitiveServicesOAuth2Api',
|
||||
);
|
||||
break;
|
||||
default:
|
||||
throw new NodeOperationError(this.getNode(), 'Invalid authentication method');
|
||||
}
|
||||
|
||||
this.logger.info(`Instantiating AzureChatOpenAI model with deployment: ${modelName}`);
|
||||
|
||||
const timeout = options.timeout;
|
||||
const model = new AzureChatOpenAI({
|
||||
// Force completions API — Azure's SDK doesn't rewrite the /responses path,
|
||||
// so the Responses API hits an invalid endpoint and causes a connection error.
|
||||
// See: https://github.com/langchain-ai/langchainjs/issues/9038
|
||||
useResponsesApi: false,
|
||||
// Model name is required so logs are correct
|
||||
// Also ensures internal logic (like mapping "maxTokens" to "maxCompletionTokens") is correct
|
||||
model: modelName,
|
||||
azureOpenAIApiDeploymentName: modelName,
|
||||
...modelConfig,
|
||||
...options,
|
||||
timeout,
|
||||
maxRetries: options.maxRetries ?? 2,
|
||||
callbacks: [new N8nLlmTracing(this)],
|
||||
configuration: {
|
||||
fetchOptions: {
|
||||
dispatcher: getProxyAgent(undefined, {
|
||||
headersTimeout: timeout,
|
||||
bodyTimeout: timeout,
|
||||
}),
|
||||
},
|
||||
},
|
||||
modelKwargs: options.responseFormat
|
||||
? {
|
||||
response_format: { type: options.responseFormat },
|
||||
}
|
||||
: undefined,
|
||||
onFailedAttempt: makeN8nLlmFailedAttemptHandler(this),
|
||||
});
|
||||
|
||||
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);
|
||||
|
||||
// Re-throw NodeOperationError directly, wrap others
|
||||
if (error instanceof NodeOperationError) {
|
||||
throw error;
|
||||
}
|
||||
|
||||
throw new NodeOperationError(
|
||||
this.getNode(),
|
||||
`Failed to initialize Azure OpenAI client: ${error.message}`,
|
||||
error,
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
+125
@@ -0,0 +1,125 @@
|
||||
import { ClientOAuth2 } from '@n8n/client-oauth2';
|
||||
import type { INode } from 'n8n-workflow';
|
||||
import { NodeOperationError } from 'n8n-workflow';
|
||||
|
||||
import { N8nOAuth2TokenCredential } from '../credentials/N8nOAuth2TokenCredential';
|
||||
import type { AzureEntraCognitiveServicesOAuth2ApiCredential } from '../types';
|
||||
|
||||
// Mock ClientOAuth2
|
||||
jest.mock('@n8n/client-oauth2', () => {
|
||||
return {
|
||||
ClientOAuth2: jest.fn().mockImplementation(() => {
|
||||
return {
|
||||
credentials: {
|
||||
getToken: jest.fn().mockResolvedValue({
|
||||
data: {
|
||||
access_token: 'fresh-test-token',
|
||||
expires_on: 1234567890,
|
||||
},
|
||||
}),
|
||||
},
|
||||
};
|
||||
}),
|
||||
};
|
||||
});
|
||||
|
||||
const mockNode: INode = {
|
||||
id: '1',
|
||||
name: 'Mock node',
|
||||
typeVersion: 2,
|
||||
type: 'n8n-nodes-base.mock',
|
||||
position: [0, 0],
|
||||
parameters: {},
|
||||
};
|
||||
|
||||
describe('N8nOAuth2TokenCredential', () => {
|
||||
let mockCredential: AzureEntraCognitiveServicesOAuth2ApiCredential;
|
||||
let credential: N8nOAuth2TokenCredential;
|
||||
|
||||
beforeEach(() => {
|
||||
// Create a mock credential with all required properties
|
||||
mockCredential = {
|
||||
authQueryParameters: '',
|
||||
authentication: 'body',
|
||||
authUrl: '',
|
||||
accessTokenUrl: '',
|
||||
grantType: 'clientCredentials',
|
||||
clientId: '',
|
||||
clientSecret: 'secret',
|
||||
customScopes: false,
|
||||
apiVersion: '2023-05-15',
|
||||
endpoint: 'https://test.openai.azure.com',
|
||||
resourceName: 'test-resource',
|
||||
oauthTokenData: {
|
||||
access_token: 'test-token',
|
||||
expires_on: 1234567890,
|
||||
ext_expires_on: 0,
|
||||
},
|
||||
scope: '',
|
||||
tenantId: '',
|
||||
};
|
||||
|
||||
credential = new N8nOAuth2TokenCredential(mockNode, mockCredential);
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
jest.clearAllMocks();
|
||||
});
|
||||
|
||||
describe('getToken', () => {
|
||||
it('should return a token when credentials are valid', async () => {
|
||||
// Act
|
||||
const result = await credential.getToken();
|
||||
|
||||
// Assert
|
||||
expect(result).toEqual({
|
||||
token: 'fresh-test-token',
|
||||
expiresOnTimestamp: 1234567890,
|
||||
});
|
||||
expect(ClientOAuth2).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
clientId: mockCredential.clientId,
|
||||
clientSecret: mockCredential.clientSecret,
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
it('should throw NodeOperationError when credentials do not contain token', async () => {
|
||||
// Arrange - remove the token
|
||||
mockCredential.oauthTokenData.access_token = '';
|
||||
credential = new N8nOAuth2TokenCredential(mockNode, mockCredential);
|
||||
|
||||
// Act & Assert
|
||||
await expect(credential.getToken()).rejects.toThrow(NodeOperationError);
|
||||
});
|
||||
|
||||
it('should throw NodeOperationError when oauthTokenData is missing', async () => {
|
||||
// Arrange - remove oauthTokenData
|
||||
const incompleteCredential = { ...mockCredential };
|
||||
// @ts-expect-error: purposely making it invalid for test
|
||||
delete incompleteCredential.oauthTokenData;
|
||||
|
||||
credential = new N8nOAuth2TokenCredential(
|
||||
mockNode,
|
||||
incompleteCredential as AzureEntraCognitiveServicesOAuth2ApiCredential,
|
||||
);
|
||||
|
||||
// Act & Assert
|
||||
await expect(credential.getToken()).rejects.toThrow(NodeOperationError);
|
||||
});
|
||||
});
|
||||
|
||||
describe('getDeploymentDetails', () => {
|
||||
it('should return deployment details from credentials', async () => {
|
||||
// Act
|
||||
const result = await credential.getDeploymentDetails();
|
||||
|
||||
// Assert
|
||||
expect(result).toEqual({
|
||||
apiVersion: '2023-05-15',
|
||||
endpoint: 'https://test.openai.azure.com',
|
||||
resourceName: 'test-resource',
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
+81
@@ -0,0 +1,81 @@
|
||||
/* eslint-disable @typescript-eslint/unbound-method */
|
||||
import { createMockExecuteFunction } from 'n8n-nodes-base/test/nodes/Helpers';
|
||||
import type { INode, ISupplyDataFunctions } from 'n8n-workflow';
|
||||
import { NodeOperationError } from 'n8n-workflow';
|
||||
|
||||
import { setupApiKeyAuthentication } from '../credentials/api-key';
|
||||
|
||||
describe('setupApiKeyAuthentication', () => {
|
||||
let ctx: ISupplyDataFunctions;
|
||||
|
||||
beforeEach(() => {
|
||||
const mockNode: INode = {
|
||||
id: '1',
|
||||
name: 'Mock node',
|
||||
typeVersion: 2,
|
||||
type: 'n8n-nodes-base.mock',
|
||||
position: [0, 0],
|
||||
parameters: {},
|
||||
};
|
||||
ctx = createMockExecuteFunction<ISupplyDataFunctions>({}, mockNode);
|
||||
ctx.logger = {
|
||||
debug: jest.fn(),
|
||||
info: jest.fn(),
|
||||
warn: jest.fn(),
|
||||
error: jest.fn(),
|
||||
};
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
jest.clearAllMocks();
|
||||
});
|
||||
|
||||
it('should return valid configuration when API key is provided', async () => {
|
||||
// Arrange
|
||||
const mockCredentials = {
|
||||
apiKey: 'test-api-key',
|
||||
resourceName: 'test-resource',
|
||||
apiVersion: '2023-05-15',
|
||||
endpoint: 'https://test.openai.azure.com',
|
||||
};
|
||||
|
||||
ctx.getCredentials = jest.fn().mockResolvedValue(mockCredentials);
|
||||
// Act
|
||||
const result = await setupApiKeyAuthentication.call(ctx, 'testCredential');
|
||||
// Assert
|
||||
expect(result).toEqual({
|
||||
azureOpenAIApiKey: 'test-api-key',
|
||||
azureOpenAIApiInstanceName: 'test-resource',
|
||||
azureOpenAIApiVersion: '2023-05-15',
|
||||
azureOpenAIEndpoint: 'https://test.openai.azure.com',
|
||||
});
|
||||
expect(ctx.getCredentials).toHaveBeenCalledWith('testCredential');
|
||||
});
|
||||
|
||||
it('should throw NodeOperationError when API key is missing', async () => {
|
||||
// Arrange
|
||||
const mockCredentials = {
|
||||
// No apiKey
|
||||
resourceName: 'test-resource',
|
||||
apiVersion: '2023-05-15',
|
||||
};
|
||||
|
||||
ctx.getCredentials = jest.fn().mockResolvedValue(mockCredentials);
|
||||
|
||||
// Act & Assert
|
||||
await expect(setupApiKeyAuthentication.call(ctx, 'testCredential')).rejects.toThrow(
|
||||
NodeOperationError,
|
||||
);
|
||||
});
|
||||
|
||||
it('should throw NodeOperationError when credential retrieval fails', async () => {
|
||||
// Arrange
|
||||
const testError = new Error('Credential fetch failed');
|
||||
ctx.getCredentials = jest.fn().mockRejectedValue(testError);
|
||||
|
||||
// Act & Assert
|
||||
await expect(setupApiKeyAuthentication.call(ctx, 'testCredential')).rejects.toThrow(
|
||||
NodeOperationError,
|
||||
);
|
||||
});
|
||||
});
|
||||
+98
@@ -0,0 +1,98 @@
|
||||
/* eslint-disable @typescript-eslint/unbound-method */
|
||||
import { createMockExecuteFunction } from 'n8n-nodes-base/test/nodes/Helpers';
|
||||
import type { INode, ISupplyDataFunctions } from 'n8n-workflow';
|
||||
import { NodeOperationError } from 'n8n-workflow';
|
||||
|
||||
import { setupOAuth2Authentication } from '../credentials/oauth2';
|
||||
import type { AzureEntraCognitiveServicesOAuth2ApiCredential } from '../types';
|
||||
|
||||
// Mock the N8nOAuth2TokenCredential
|
||||
jest.mock('../credentials/N8nOAuth2TokenCredential', () => ({
|
||||
N8nOAuth2TokenCredential: jest.fn().mockImplementation(() => ({
|
||||
getToken: jest.fn().mockResolvedValue({
|
||||
token: 'test-token',
|
||||
expiresOnTimestamp: 1234567890,
|
||||
}),
|
||||
getDeploymentDetails: jest.fn().mockResolvedValue({
|
||||
apiVersion: '2023-05-15',
|
||||
endpoint: 'https://test.openai.azure.com',
|
||||
resourceName: 'test-resource',
|
||||
}),
|
||||
})),
|
||||
}));
|
||||
|
||||
const mockNode: INode = {
|
||||
id: '1',
|
||||
name: 'Mock node',
|
||||
typeVersion: 2,
|
||||
type: 'n8n-nodes-base.mock',
|
||||
position: [0, 0],
|
||||
parameters: {},
|
||||
};
|
||||
|
||||
describe('setupOAuth2Authentication', () => {
|
||||
let mockCredential: AzureEntraCognitiveServicesOAuth2ApiCredential;
|
||||
let ctx: ISupplyDataFunctions;
|
||||
beforeEach(() => {
|
||||
// Set up a mock credential
|
||||
mockCredential = {
|
||||
authQueryParameters: '',
|
||||
authentication: 'body', // Set valid authentication type
|
||||
authUrl: '',
|
||||
accessTokenUrl: '', // Added missing property
|
||||
grantType: 'clientCredentials', // Corrected grant type value
|
||||
clientId: '',
|
||||
customScopes: false,
|
||||
apiVersion: '2023-05-15',
|
||||
endpoint: 'https://test.openai.azure.com',
|
||||
resourceName: 'test-resource',
|
||||
oauthTokenData: {
|
||||
access_token: 'test-token',
|
||||
expires_on: 1234567890,
|
||||
ext_expires_on: 0,
|
||||
},
|
||||
scope: '',
|
||||
tenantId: '',
|
||||
};
|
||||
ctx = createMockExecuteFunction<ISupplyDataFunctions>({}, mockNode);
|
||||
ctx.getCredentials = jest.fn().mockResolvedValue(mockCredential);
|
||||
ctx.logger = {
|
||||
debug: jest.fn(),
|
||||
info: jest.fn(),
|
||||
warn: jest.fn(),
|
||||
error: jest.fn(),
|
||||
};
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
jest.clearAllMocks();
|
||||
});
|
||||
|
||||
it('should return token provider and deployment details when successful', async () => {
|
||||
// Act
|
||||
const result = await setupOAuth2Authentication.call(ctx, 'testCredential');
|
||||
|
||||
// Assert
|
||||
expect(result).toHaveProperty('azureADTokenProvider');
|
||||
expect(typeof result.azureADTokenProvider).toBe('function');
|
||||
expect(result).toEqual(
|
||||
expect.objectContaining({
|
||||
azureOpenAIApiInstanceName: 'test-resource',
|
||||
azureOpenAIApiVersion: '2023-05-15',
|
||||
azureOpenAIEndpoint: 'https://test.openai.azure.com',
|
||||
}),
|
||||
);
|
||||
expect(ctx.getCredentials).toHaveBeenCalledWith('testCredential');
|
||||
});
|
||||
|
||||
it('should throw NodeOperationError when credential retrieval fails', async () => {
|
||||
// Arrange
|
||||
const testError = new Error('Credential fetch failed');
|
||||
ctx.getCredentials = jest.fn().mockRejectedValue(testError);
|
||||
|
||||
// Act & Assert
|
||||
await expect(setupOAuth2Authentication.call(ctx, 'testCredential')).rejects.toThrow(
|
||||
NodeOperationError,
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="256" height="242" preserveAspectRatio="xMidYMid"><defs><linearGradient id="a" x1="58.972%" x2="37.191%" y1="7.411%" y2="103.762%"><stop offset="0%" stop-color="#114A8B"/><stop offset="100%" stop-color="#0669BC"/></linearGradient><linearGradient id="b" x1="59.719%" x2="52.691%" y1="52.313%" y2="54.864%"><stop offset="0%" stop-opacity=".3"/><stop offset="7.1%" stop-opacity=".2"/><stop offset="32.1%" stop-opacity=".1"/><stop offset="62.3%" stop-opacity=".05"/><stop offset="100%" stop-opacity="0"/></linearGradient><linearGradient id="c" x1="37.279%" x2="62.473%" y1="4.6%" y2="99.979%"><stop offset="0%" stop-color="#3CCBF4"/><stop offset="100%" stop-color="#2892DF"/></linearGradient></defs><path fill="url(#a)" d="M85.343.003h75.753L82.457 233a12.08 12.08 0 0 1-11.442 8.216H12.06A12.06 12.06 0 0 1 .633 225.303L73.898 8.219A12.08 12.08 0 0 1 85.343 0z"/><path fill="#0078D4" d="M195.423 156.282H75.297a5.56 5.56 0 0 0-3.796 9.627l77.19 72.047a12.14 12.14 0 0 0 8.28 3.26h68.02z"/><path fill="url(#b)" d="M85.343.003a11.98 11.98 0 0 0-11.471 8.376L.723 225.105a12.045 12.045 0 0 0 11.37 16.112h60.475a12.93 12.93 0 0 0 9.921-8.437l14.588-42.991 52.105 48.6a12.33 12.33 0 0 0 7.757 2.828h67.766l-29.721-84.935-86.643.02L161.37.003z"/><path fill="url(#c)" d="M182.098 8.207A12.06 12.06 0 0 0 170.67.003H86.245c5.175 0 9.773 3.301 11.428 8.204L170.94 225.3a12.062 12.062 0 0 1-11.428 15.92h84.429a12.062 12.062 0 0 0 11.425-15.92z"/></svg>
|
||||
|
After Width: | Height: | Size: 1.5 KiB |
+61
@@ -0,0 +1,61 @@
|
||||
import type { TokenCredential, AccessToken } from '@azure/identity';
|
||||
import type { ClientOAuth2TokenData } from '@n8n/client-oauth2';
|
||||
import { ClientOAuth2 } from '@n8n/client-oauth2';
|
||||
import type { INode } from 'n8n-workflow';
|
||||
import { NodeOperationError } from 'n8n-workflow';
|
||||
|
||||
import type { AzureEntraCognitiveServicesOAuth2ApiCredential } from '../types';
|
||||
/**
|
||||
* Adapts n8n's credential retrieval into the TokenCredential interface expected by @azure/identity
|
||||
*/
|
||||
export class N8nOAuth2TokenCredential implements TokenCredential {
|
||||
constructor(
|
||||
private node: INode,
|
||||
private credential: AzureEntraCognitiveServicesOAuth2ApiCredential,
|
||||
) {}
|
||||
|
||||
/**
|
||||
* Gets an access token from OAuth credential
|
||||
*/
|
||||
async getToken(): Promise<AccessToken | null> {
|
||||
try {
|
||||
if (!this.credential?.oauthTokenData?.access_token) {
|
||||
throw new NodeOperationError(this.node, 'Failed to retrieve access token');
|
||||
}
|
||||
const oAuthClient = new ClientOAuth2({
|
||||
clientId: this.credential.clientId,
|
||||
clientSecret: this.credential.clientSecret,
|
||||
accessTokenUri: this.credential.accessTokenUrl,
|
||||
scopes: this.credential.scope?.split(' '),
|
||||
authentication: this.credential.authentication,
|
||||
authorizationUri: this.credential.authUrl,
|
||||
additionalBodyProperties: {
|
||||
resource: 'https://cognitiveservices.azure.com/',
|
||||
},
|
||||
});
|
||||
|
||||
const token = await oAuthClient.credentials.getToken();
|
||||
const data = token.data as ClientOAuth2TokenData & {
|
||||
expires_on: number;
|
||||
};
|
||||
return {
|
||||
token: data.access_token,
|
||||
expiresOnTimestamp: data.expires_on,
|
||||
};
|
||||
} catch (error) {
|
||||
// Re-throw with better error message
|
||||
throw new NodeOperationError(this.node, 'Failed to retrieve OAuth2 access token', error);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the deployment details from the credential
|
||||
*/
|
||||
async getDeploymentDetails() {
|
||||
return {
|
||||
apiVersion: this.credential.apiVersion,
|
||||
endpoint: this.credential.endpoint,
|
||||
resourceName: this.credential.resourceName,
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
import { NodeOperationError, OperationalError, type ISupplyDataFunctions } from 'n8n-workflow';
|
||||
|
||||
import type { AzureOpenAIApiKeyModelConfig } from '../types';
|
||||
|
||||
/**
|
||||
* Handles API Key authentication setup for Azure OpenAI
|
||||
*/
|
||||
export async function setupApiKeyAuthentication(
|
||||
this: ISupplyDataFunctions,
|
||||
credentialName: string,
|
||||
): Promise<AzureOpenAIApiKeyModelConfig> {
|
||||
try {
|
||||
// Get Azure OpenAI Config (Endpoint, Version, etc.)
|
||||
const configCredentials = await this.getCredentials<{
|
||||
apiKey?: string;
|
||||
resourceName: string;
|
||||
apiVersion: string;
|
||||
endpoint?: string;
|
||||
}>(credentialName);
|
||||
|
||||
if (!configCredentials.apiKey) {
|
||||
throw new NodeOperationError(
|
||||
this.getNode(),
|
||||
'API Key is missing in the selected Azure OpenAI API credential. Please configure the API Key or choose Entra ID authentication.',
|
||||
);
|
||||
}
|
||||
|
||||
this.logger.info('Using API Key authentication for Azure OpenAI.');
|
||||
|
||||
return {
|
||||
azureOpenAIApiKey: configCredentials.apiKey,
|
||||
azureOpenAIApiInstanceName: configCredentials.resourceName,
|
||||
azureOpenAIApiVersion: configCredentials.apiVersion,
|
||||
azureOpenAIEndpoint: configCredentials.endpoint,
|
||||
};
|
||||
} catch (error) {
|
||||
if (error instanceof OperationalError) {
|
||||
throw error;
|
||||
}
|
||||
|
||||
this.logger.error(`Error setting up API Key authentication: ${error.message}`, error);
|
||||
|
||||
throw new NodeOperationError(this.getNode(), 'Failed to retrieve API Key', error);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
import { getBearerTokenProvider } from '@azure/identity';
|
||||
import { NodeOperationError, type ISupplyDataFunctions } from 'n8n-workflow';
|
||||
|
||||
import { N8nOAuth2TokenCredential } from './N8nOAuth2TokenCredential';
|
||||
import type {
|
||||
AzureEntraCognitiveServicesOAuth2ApiCredential,
|
||||
AzureOpenAIOAuth2ModelConfig,
|
||||
} from '../types';
|
||||
|
||||
const AZURE_OPENAI_SCOPE = 'https://cognitiveservices.azure.com/.default';
|
||||
/**
|
||||
* Creates Entra ID (OAuth2) authentication for Azure OpenAI
|
||||
*/
|
||||
export async function setupOAuth2Authentication(
|
||||
this: ISupplyDataFunctions,
|
||||
credentialName: string,
|
||||
): Promise<AzureOpenAIOAuth2ModelConfig> {
|
||||
try {
|
||||
const credential =
|
||||
await this.getCredentials<AzureEntraCognitiveServicesOAuth2ApiCredential>(credentialName);
|
||||
// Create a TokenCredential
|
||||
const entraTokenCredential = new N8nOAuth2TokenCredential(this.getNode(), credential);
|
||||
const deploymentDetails = await entraTokenCredential.getDeploymentDetails();
|
||||
|
||||
// Use getBearerTokenProvider to create the function LangChain expects
|
||||
// Pass the required scope for Azure Cognitive Services
|
||||
const azureADTokenProvider = getBearerTokenProvider(entraTokenCredential, AZURE_OPENAI_SCOPE);
|
||||
|
||||
this.logger.debug('Successfully created Azure AD Token Provider.');
|
||||
|
||||
return {
|
||||
azureADTokenProvider,
|
||||
azureOpenAIApiInstanceName: deploymentDetails.resourceName,
|
||||
azureOpenAIApiVersion: deploymentDetails.apiVersion,
|
||||
azureOpenAIEndpoint: deploymentDetails.endpoint,
|
||||
};
|
||||
} catch (error) {
|
||||
this.logger.error(`Error setting up Entra ID authentication: ${error.message}`, error);
|
||||
|
||||
throw new NodeOperationError(
|
||||
this.getNode(),
|
||||
`Error setting up Entra ID authentication: ${error.message}`,
|
||||
error,
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,137 @@
|
||||
import type { INodeProperties } from 'n8n-workflow';
|
||||
import { NodeConnectionTypes } from 'n8n-workflow';
|
||||
|
||||
import { getConnectionHintNoticeField } from '@n8n/ai-utilities';
|
||||
|
||||
import { AuthenticationType } from './types';
|
||||
|
||||
export const properties: INodeProperties[] = [
|
||||
// eslint-disable-next-line n8n-nodes-base/node-param-default-missing
|
||||
{
|
||||
displayName: 'Authentication',
|
||||
name: 'authentication',
|
||||
type: 'options',
|
||||
default: AuthenticationType.ApiKey,
|
||||
options: [
|
||||
{
|
||||
name: 'API Key',
|
||||
value: AuthenticationType.ApiKey,
|
||||
},
|
||||
{
|
||||
name: 'Azure Entra ID (OAuth2)',
|
||||
value: AuthenticationType.EntraOAuth2,
|
||||
},
|
||||
],
|
||||
},
|
||||
getConnectionHintNoticeField([NodeConnectionTypes.AiChain, NodeConnectionTypes.AiAgent]),
|
||||
{
|
||||
displayName:
|
||||
'If using JSON response format, you must include word "json" in the prompt in your chain or agent. Also, make sure to select latest models released post November 2023.',
|
||||
name: 'notice',
|
||||
type: 'notice',
|
||||
default: '',
|
||||
displayOptions: {
|
||||
show: {
|
||||
'/options.responseFormat': ['json_object'],
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
displayName: 'Model (Deployment) Name',
|
||||
name: 'model',
|
||||
type: 'string',
|
||||
description: 'The name of the model(deployment) to use (e.g., gpt-4, gpt-35-turbo)',
|
||||
required: true,
|
||||
default: '',
|
||||
},
|
||||
{
|
||||
displayName: 'Options',
|
||||
name: 'options',
|
||||
placeholder: 'Add Option',
|
||||
description: 'Additional options to add',
|
||||
type: 'collection',
|
||||
default: {},
|
||||
options: [
|
||||
{
|
||||
displayName: 'Frequency Penalty',
|
||||
name: 'frequencyPenalty',
|
||||
default: 0,
|
||||
typeOptions: { maxValue: 2, minValue: -2, numberPrecision: 1 },
|
||||
description:
|
||||
"Positive values penalize new tokens based on their existing frequency in the text so far, decreasing the model's likelihood to repeat the same line verbatim",
|
||||
type: 'number',
|
||||
},
|
||||
{
|
||||
displayName: 'Maximum Number of Tokens',
|
||||
name: 'maxTokens',
|
||||
default: -1,
|
||||
description:
|
||||
'The maximum number of tokens to generate in the completion. Most models have a context length of 2048 tokens (except for the newest models, which support 32,768). Use -1 for default.',
|
||||
type: 'number',
|
||||
typeOptions: {
|
||||
maxValue: 128000,
|
||||
},
|
||||
},
|
||||
{
|
||||
displayName: 'Response Format',
|
||||
name: 'responseFormat',
|
||||
default: 'text',
|
||||
type: 'options',
|
||||
options: [
|
||||
{
|
||||
name: 'Text',
|
||||
value: 'text',
|
||||
description: 'Regular text response',
|
||||
},
|
||||
{
|
||||
name: 'JSON',
|
||||
value: 'json_object',
|
||||
description:
|
||||
'Enables JSON mode, which should guarantee the message the model generates is valid JSON',
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
displayName: 'Presence Penalty',
|
||||
name: 'presencePenalty',
|
||||
default: 0,
|
||||
typeOptions: { maxValue: 2, minValue: -2, numberPrecision: 1 },
|
||||
description:
|
||||
"Positive values penalize new tokens based on whether they appear in the text so far, increasing the model's likelihood to talk about new topics",
|
||||
type: 'number',
|
||||
},
|
||||
{
|
||||
displayName: 'Sampling Temperature',
|
||||
name: 'temperature',
|
||||
default: 0.7,
|
||||
typeOptions: { maxValue: 2, minValue: 0, numberPrecision: 1 }, // Max temp can be 2
|
||||
description:
|
||||
'Controls randomness: Lowering results in less random completions. As the temperature approaches zero, the model will become deterministic and repetitive.',
|
||||
type: 'number',
|
||||
},
|
||||
{
|
||||
displayName: 'Timeout (Ms)',
|
||||
name: 'timeout',
|
||||
default: 60000,
|
||||
description: 'Maximum amount of time a request is allowed to take in milliseconds',
|
||||
type: 'number',
|
||||
},
|
||||
{
|
||||
displayName: 'Max Retries',
|
||||
name: 'maxRetries',
|
||||
default: 2,
|
||||
description: 'Maximum number of retries to attempt on failure',
|
||||
type: 'number',
|
||||
},
|
||||
{
|
||||
displayName: 'Top P',
|
||||
name: 'topP',
|
||||
default: 1,
|
||||
typeOptions: { maxValue: 1, minValue: 0, numberPrecision: 1 },
|
||||
description:
|
||||
'Controls diversity via nucleus sampling: 0.5 means half of all likelihood-weighted options are considered. We generally recommend altering this or temperature but not both.',
|
||||
type: 'number',
|
||||
},
|
||||
],
|
||||
},
|
||||
];
|
||||
@@ -0,0 +1,94 @@
|
||||
import type { OAuth2CredentialData } from '@n8n/client-oauth2';
|
||||
/**
|
||||
* Common interfaces for Azure OpenAI configuration
|
||||
*/
|
||||
|
||||
/**
|
||||
* Basic Azure OpenAI API configuration options
|
||||
*/
|
||||
export interface AzureOpenAIConfig {
|
||||
apiVersion: string;
|
||||
resourceName: string;
|
||||
endpoint?: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Configuration for API Key authentication
|
||||
*/
|
||||
export interface AzureOpenAIApiKeyConfig extends AzureOpenAIConfig {
|
||||
apiKey: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Azure OpenAI node options
|
||||
*/
|
||||
export interface AzureOpenAIOptions {
|
||||
frequencyPenalty?: number;
|
||||
maxTokens?: number;
|
||||
maxRetries?: number;
|
||||
timeout?: number;
|
||||
presencePenalty?: number;
|
||||
temperature?: number;
|
||||
topP?: number;
|
||||
responseFormat?: 'text' | 'json_object';
|
||||
}
|
||||
|
||||
/**
|
||||
* Base model configuration that can be passed to AzureChatOpenAI constructor
|
||||
*/
|
||||
export interface AzureOpenAIBaseModelConfig {
|
||||
azureOpenAIApiInstanceName: string;
|
||||
azureOpenAIApiVersion: string;
|
||||
azureOpenAIEndpoint?: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* API Key model configuration that can be passed to AzureChatOpenAI constructor
|
||||
*/
|
||||
export interface AzureOpenAIApiKeyModelConfig extends AzureOpenAIBaseModelConfig {
|
||||
azureOpenAIApiKey: string;
|
||||
azureADTokenProvider?: undefined;
|
||||
}
|
||||
|
||||
/**
|
||||
* OAuth2 model configuration that can be passed to AzureChatOpenAI constructor
|
||||
*/
|
||||
export interface AzureOpenAIOAuth2ModelConfig extends AzureOpenAIBaseModelConfig {
|
||||
azureOpenAIApiKey?: undefined;
|
||||
azureADTokenProvider: () => Promise<string>;
|
||||
}
|
||||
|
||||
/**
|
||||
* Authentication types supported by Azure OpenAI node
|
||||
*/
|
||||
export const enum AuthenticationType {
|
||||
ApiKey = 'azureOpenAiApi',
|
||||
EntraOAuth2 = 'azureEntraCognitiveServicesOAuth2Api',
|
||||
}
|
||||
|
||||
/**
|
||||
* Error types for Azure OpenAI node
|
||||
*/
|
||||
export const enum AzureOpenAIErrorType {
|
||||
AuthenticationError = 'AuthenticationError',
|
||||
ConfigurationError = 'ConfigurationError',
|
||||
APIError = 'APIError',
|
||||
UnknownError = 'UnknownError',
|
||||
}
|
||||
|
||||
/**
|
||||
* OAuth2 credential type used by Azure OpenAI node
|
||||
*/
|
||||
type TokenData = OAuth2CredentialData['oauthTokenData'] & {
|
||||
expires_on: number;
|
||||
ext_expires_on: number;
|
||||
};
|
||||
export type AzureEntraCognitiveServicesOAuth2ApiCredential = OAuth2CredentialData & {
|
||||
customScopes: boolean;
|
||||
authentication: string;
|
||||
apiVersion: string;
|
||||
endpoint: string;
|
||||
resourceName: string;
|
||||
tenantId: string;
|
||||
oauthTokenData: TokenData;
|
||||
};
|
||||
Reference in New Issue
Block a user