"use strict";
/**
 * OpenAI Provider Plugin for Native AI
 *
 * This plugin implements the OpenAI provider for the Native AI plugin system.
 * It demonstrates how to create a provider plugin that can be used with the
 * Native AI plugin system in BFUI.
 */
Object.defineProperty(exports, "__esModule", { value: true });
exports.OpenAIProviderPlugin = void 0;
/**
 * OpenAI Provider Plugin
 */
class OpenAIProviderPlugin {
    constructor() {
        // Plugin metadata
        this.id = 'openai-provider';
        this.name = 'OpenAI Provider';
        this.version = '1.0.0';
        this.type = 'provider';
        this.capabilities = [
            'chat',
            'completion',
            'streaming',
            'embeddings',
            'vision',
            'toolCalls'
        ];
        this.metadata = {
            author: 'BFUI Team',
            description: 'OpenAI provider for Native AI',
            website: 'https://openai.com/',
            license: 'MIT'
        };
        // Plugin state
        this.initialized = false;
        this.context = null;
        this.apiKey = null;
        this.baseUrl = 'https://api.openai.com/v1';
        this.models = [
            {
                id: 'gpt-4-turbo-preview',
                name: 'GPT-4 Turbo',
                capabilities: ['chat', 'streaming', 'vision', 'toolCalls'],
                contextWindow: 128000,
                maxOutputTokens: 4096,
                metadata: {
                    version: '0124',
                    releaseDate: '2024-01-25',
                    architecture: 'transformer'
                }
            },
            {
                id: 'gpt-4o',
                name: 'GPT-4o',
                capabilities: ['chat', 'streaming', 'vision', 'toolCalls'],
                contextWindow: 128000,
                maxOutputTokens: 4096,
                metadata: {
                    version: '0314',
                    releaseDate: '2024-03-14',
                    architecture: 'transformer'
                }
            },
            {
                id: 'gpt-3.5-turbo',
                name: 'GPT-3.5 Turbo',
                capabilities: ['chat', 'streaming', 'toolCalls'],
                contextWindow: 16385,
                maxOutputTokens: 4096,
                metadata: {
                    version: '0125',
                    releaseDate: '2024-01-25',
                    architecture: 'transformer'
                }
            },
            {
                id: 'text-embedding-3-small',
                name: 'Text Embedding 3 Small',
                capabilities: ['embeddings'],
                contextWindow: 8191,
                metadata: {
                    version: '3',
                    releaseDate: '2024-01-25',
                    architecture: 'transformer',
                    dimensions: 1536
                }
            },
            {
                id: 'text-embedding-3-large',
                name: 'Text Embedding 3 Large',
                capabilities: ['embeddings'],
                contextWindow: 8191,
                metadata: {
                    version: '3',
                    releaseDate: '2024-01-25',
                    architecture: 'transformer',
                    dimensions: 3072
                }
            }
        ];
    }
    /**
     * Initialize the plugin
     */
    async initialize(context) {
        if (this.initialized) {
            return;
        }
        this.context = context;
        // Get configuration
        const config = context.config['openai-provider'] || {};
        this.apiKey = config.apiKey || process.env.OPENAI_API_KEY;
        this.baseUrl = config.baseUrl || this.baseUrl;
        if (!this.apiKey) {
            throw new Error('OpenAI API key not provided');
        }
        this.initialized = true;
        context.logger.info(`Initialized ${this.name} plugin`);
    }
    /**
     * Check if the plugin is initialized
     */
    isInitialized() {
        return this.initialized;
    }
    /**
     * Shutdown the plugin
     */
    async shutdown() {
        this.initialized = false;
        if (this.context) {
            this.context.logger.info(`Shut down ${this.name} plugin`);
        }
    }
    /**
     * Execute a request against the provider
     */
    async execute(request, options) {
        if (!this.initialized || !this.context) {
            throw new Error('Plugin not initialized');
        }
        const logger = this.context.logger;
        logger.info(`Executing request against ${this.name}`, { request });
        // Extract request parameters
        const model = request.model || 'gpt-4o';
        const messages = request.messages || [];
        const parameters = request.parameters || {};
        const endpoint = options?.endpoint || 'chat/completions';
        try {
            // For embeddings endpoint
            if (endpoint === 'embeddings') {
                const embeddingModel = model || 'text-embedding-3-small';
                // Mock embedding response for demo purposes
                const dimensions = embeddingModel.includes('large') ? 3072 : 1536;
                const mockEmbedding = Array(dimensions).fill(0).map(() => Math.random() - 0.5);
                const embeddings = Array.isArray(request.texts)
                    ? request.texts.map(() => Array(dimensions).fill(0).map(() => Math.random() - 0.5))
                    : [mockEmbedding];
                const response = {
                    model: embeddingModel,
                    embeddings,
                    usage: {
                        prompt_tokens: request.texts ? request.texts.length * 100 : 100,
                        total_tokens: request.texts ? request.texts.length * 100 : 100
                    }
                };
                logger.info(`Embeddings request executed successfully against ${this.name}`);
                return response;
            }
            // For chat completions endpoint
            // Create OpenAI API request format
            const apiRequest = {
                model: model,
                messages: messages,
                max_tokens: parameters.max_tokens || 1000,
                temperature: parameters.temperature || 0.7,
                stream: false,
                tools: request.tools || undefined,
                tool_choice: request.tool_choice || undefined
            };
            // Mock response for demo purposes
            // In a real implementation, this would make an API call to OpenAI
            const mockResponse = {
                id: `chatcmpl-${Date.now()}`,
                object: 'chat.completion',
                created: Math.floor(Date.now() / 1000),
                model: model,
                choices: [
                    {
                        index: 0,
                        message: {
                            role: 'assistant',
                            content: "This is a mock response from the OpenAI provider plugin. In a real implementation, this would be the response from the OpenAI API.",
                        },
                        finish_reason: 'stop'
                    }
                ],
                usage: {
                    prompt_tokens: 100,
                    completion_tokens: 50,
                    total_tokens: 150
                }
            };
            // If tools were requested, simulate a tool call
            if (request.tools && request.tools.length > 0) {
                mockResponse.choices[0].message.tool_calls = [
                    {
                        id: `call_${Date.now()}`,
                        type: 'function',
                        function: {
                            name: request.tools[0].name,
                            arguments: JSON.stringify({ argument: "value" })
                        }
                    }
                ];
                mockResponse.choices[0].message.content = null;
                mockResponse.choices[0].finish_reason = 'tool_calls';
            }
            logger.info(`Request executed successfully against ${this.name}`);
            return mockResponse;
        }
        catch (error) {
            logger.error(`Error executing request against ${this.name}`, { error });
            throw error;
        }
    }
    /**
     * Execute a streaming request against the provider
     */
    async executeStreaming(request, handler, options) {
        if (!this.initialized || !this.context) {
            throw new Error('Plugin not initialized');
        }
        const logger = this.context.logger;
        logger.info(`Executing streaming request against ${this.name}`, { request });
        // Extract request parameters
        const model = request.model || 'gpt-4o';
        const messages = request.messages || [];
        const parameters = request.parameters || {};
        try {
            // Mock streaming response for demo purposes
            // In a real implementation, this would stream from the OpenAI API
            const chunks = [
                "This is a mock ",
                "streaming response ",
                "from the OpenAI ",
                "provider plugin. ",
                "In a real implementation, ",
                "this would stream from ",
                "the OpenAI API."
            ];
            // Send chunks with a delay
            for (let i = 0; i < chunks.length; i++) {
                const isLast = i === chunks.length - 1;
                // Format chunk like OpenAI streaming format
                const chunkData = {
                    id: `chatcmpl-${Date.now()}`,
                    object: 'chat.completion.chunk',
                    created: Math.floor(Date.now() / 1000),
                    model: model,
                    choices: [
                        {
                            index: 0,
                            delta: {
                                content: chunks[i]
                            },
                            finish_reason: isLast ? 'stop' : null
                        }
                    ]
                };
                // Send chunk through handler
                handler.onChunk({
                    content: chunks[i],
                    done: isLast,
                    data: chunkData
                });
                // Add delay between chunks (except for the last one)
                if (!isLast) {
                    await new Promise(resolve => setTimeout(resolve, 100));
                }
            }
            // Send completion with full response
            handler.onComplete({
                id: `chatcmpl-${Date.now()}`,
                model: model,
                content: chunks.join(''),
                usage: {
                    prompt_tokens: 100,
                    completion_tokens: 50,
                    total_tokens: 150
                }
            });
            logger.info(`Streaming request executed successfully against ${this.name}`);
        }
        catch (error) {
            logger.error(`Error executing streaming request against ${this.name}`, { error });
            handler.onError({
                error: error.message || 'Unknown error',
                model: model,
                provider: this.id
            });
            throw error;
        }
    }
    /**
     * Get provider capabilities
     */
    getCapabilities() {
        return {
            streaming: true,
            toolCalls: true,
            embeddings: true,
            vision: true
        };
    }
    /**
     * Get provider models
     */
    getModels() {
        return this.models;
    }
}
exports.OpenAIProviderPlugin = OpenAIProviderPlugin;
//# sourceMappingURL=openai-provider-plugin.js.map