"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.LmChatGoogleVertex = void 0;
const resource_manager_1 = require("@google-cloud/resource-manager");
const google_vertexai_1 = require("@langchain/google-vertexai");
const utilities_1 = require("n8n-nodes-base/dist/utils/utilities");
const n8n_workflow_1 = require("n8n-workflow");
const error_handling_1 = require("./error-handling");
const additional_options_1 = require("../gemini-common/additional-options");
const ai_utilities_1 = require("@n8n/ai-utilities");
class LmChatGoogleVertex {
    constructor() {
        this.description = {
            displayName: 'Google Vertex Chat Model',
            name: 'lmChatGoogleVertex',
            icon: 'file:google.svg',
            group: ['transform'],
            version: 1,
            description: 'Chat Model Google Vertex',
            defaults: {
                name: 'Google Vertex 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.lmchatgooglevertex/',
                        },
                    ],
                },
            },
            inputs: [],
            outputs: [n8n_workflow_1.NodeConnectionTypes.AiLanguageModel],
            outputNames: ['Model'],
            credentials: [
                {
                    name: 'googleApi',
                    required: true,
                },
            ],
            properties: [
                (0, ai_utilities_1.getConnectionHintNoticeField)([n8n_workflow_1.NodeConnectionTypes.AiChain, n8n_workflow_1.NodeConnectionTypes.AiAgent]),
                {
                    displayName: 'Project ID',
                    name: 'projectId',
                    type: 'resourceLocator',
                    default: { mode: 'list', value: '' },
                    required: true,
                    description: 'Select or enter your Google Cloud project ID',
                    modes: [
                        {
                            displayName: 'From List',
                            name: 'list',
                            type: 'list',
                            typeOptions: {
                                searchListMethod: 'gcpProjectsList',
                            },
                        },
                        {
                            displayName: 'ID',
                            name: 'id',
                            type: 'string',
                        },
                    ],
                },
                {
                    displayName: 'Model Name',
                    name: 'modelName',
                    type: 'string',
                    description: 'The model which will generate the completion. <a href="https://cloud.google.com/vertex-ai/generative-ai/docs/learn/models">Learn more</a>.',
                    default: 'gemini-2.5-flash',
                    builderHint: {
                        propertyHint: 'Default to the latest flagship Gemini on Vertex (gemini-3.1-pro). Use gemini-3.1-flash-lite for cost-efficient builds. Avoid Gemini 2.x, 1.x, and earlier.',
                    },
                },
                (0, additional_options_1.getAdditionalOptions)({ supportsThinkingBudget: true }),
            ],
        };
        this.methods = {
            listSearch: {
                async gcpProjectsList() {
                    const results = [];
                    const credentials = await this.getCredentials('googleApi');
                    const privateKey = (0, utilities_1.formatPrivateKey)(credentials.privateKey);
                    const email = credentials.email.trim();
                    const client = new resource_manager_1.ProjectsClient({
                        credentials: {
                            client_email: email,
                            private_key: privateKey,
                        },
                    });
                    const [projects] = await client.searchProjects();
                    for (const project of projects) {
                        if (project.projectId) {
                            results.push({
                                name: project.displayName ?? project.projectId,
                                value: project.projectId,
                            });
                        }
                    }
                    return { results };
                },
            },
        };
    }
    async supplyData(itemIndex) {
        const credentials = await this.getCredentials('googleApi');
        const privateKey = (0, utilities_1.formatPrivateKey)(credentials.privateKey);
        const email = credentials.email.trim();
        const region = credentials.region;
        const modelName = this.getNodeParameter('modelName', itemIndex);
        const projectId = this.getNodeParameter('projectId', itemIndex, '', {
            extractValue: true,
        });
        const options = this.getNodeParameter('options', itemIndex, {
            maxOutputTokens: 2048,
            temperature: 0.4,
            topK: 40,
            topP: 0.9,
        });
        (0, n8n_workflow_1.validateNodeParameters)(options, {
            maxOutputTokens: { type: 'number', required: false },
            temperature: { type: 'number', required: false },
            topK: { type: 'number', required: false },
            topP: { type: 'number', required: false },
            thinkingBudget: { type: 'number', required: false },
        }, this.getNode());
        const safetySettings = this.getNodeParameter('options.safetySettings.values', itemIndex, null);
        try {
            const modelConfig = {
                authOptions: {
                    projectId,
                    credentials: {
                        client_email: email,
                        private_key: privateKey,
                    },
                },
                location: region,
                model: modelName,
                topK: options.topK,
                topP: options.topP,
                temperature: options.temperature,
                maxOutputTokens: options.maxOutputTokens,
                safetySettings,
                callbacks: [new ai_utilities_1.N8nLlmTracing(this)],
                onFailedAttempt: (0, ai_utilities_1.makeN8nLlmFailedAttemptHandler)(this, (error) => {
                    const customError = (0, error_handling_1.makeErrorFromStatus)(Number(error?.response?.status), {
                        modelName,
                    });
                    if (customError) {
                        throw new n8n_workflow_1.NodeOperationError(this.getNode(), error, customError);
                    }
                    throw error;
                }),
            };
            if (options.thinkingBudget !== undefined) {
                modelConfig.thinkingBudget = options.thinkingBudget;
            }
            const model = new google_vertexai_1.ChatVertexAI(modelConfig);
            return {
                response: model,
            };
        }
        catch (e) {
            if (e?.message?.startsWith('Unable to verify model params')) {
                throw new n8n_workflow_1.NodeOperationError(this.getNode(), e, {
                    message: 'Unsupported model',
                    description: "Only models starting with 'gemini' are supported.",
                });
            }
            throw new n8n_workflow_1.NodeOperationError(this.getNode(), e, {
                message: 'Invalid options',
                description: e.message,
            });
        }
    }
}
exports.LmChatGoogleVertex = LmChatGoogleVertex;
//# sourceMappingURL=LmChatGoogleVertex.node.js.map