"use strict";
/**
 * NVIDIA API Adapter
 * Handles communication with NVIDIA models (Kimi K2.5, Gemma 4, MoE models)
 */
Object.defineProperty(exports, "__esModule", { value: true });
exports.MODEL_METADATA = exports.NVIDIAAdapter = void 0;
exports.getModelInfo = getModelInfo;
class NVIDIAAdapter {
    config;
    constructor(config) {
        this.config = {
            ...config,
            baseUrl: config.baseUrl || 'https://integrate.api.nvidia.com/v1'
        };
    }
    /**
     * Send chat completion request to NVIDIA API
     */
    async chat(messages, options = {}) {
        const model = options.model || this.config.defaultModel;
        // Validate model
        if (!this.config.availableModels.includes(model)) {
            throw new Error(`Model "${model}" not in available models. Choose from: ${this.config.availableModels.join(', ')}`);
        }
        try {
            const response = await fetch(`${this.config.baseUrl}/chat/completions`, {
                method: 'POST',
                headers: {
                    'Authorization': `Bearer ${this.config.apiKey}`,
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({
                    model,
                    messages,
                    temperature: options.temperature ?? 0.7,
                    max_tokens: options.maxTokens ?? 4096,
                    stream: options.stream ?? false
                })
            });
            if (!response.ok) {
                const error = await response.text();
                throw new Error(`NVIDIA API error (${response.status}): ${error}`);
            }
            const data = await response.json();
            return {
                content: data.choices[0].message.content,
                model: data.model,
                usage: data.usage ? {
                    promptTokens: data.usage.prompt_tokens,
                    completionTokens: data.usage.completion_tokens,
                    totalTokens: data.usage.total_tokens
                } : undefined
            };
        }
        catch (error) {
            if (error instanceof Error) {
                throw error;
            }
            throw new Error(`NVIDIA API request failed: ${String(error)}`);
        }
    }
    /**
     * Stream chat completion for real-time responses
     */
    async *stream(messages, options = {}) {
        const model = options.model || this.config.defaultModel;
        try {
            const response = await fetch(`${this.config.baseUrl}/chat/completions`, {
                method: 'POST',
                headers: {
                    'Authorization': `Bearer ${this.config.apiKey}`,
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({
                    model,
                    messages,
                    temperature: options.temperature ?? 0.7,
                    max_tokens: options.maxTokens ?? 4096,
                    stream: true
                })
            });
            if (!response.ok) {
                throw new Error(`NVIDIA API error: ${response.statusText}`);
            }
            const reader = response.body?.getReader();
            if (!reader) {
                throw new Error('Response body is null');
            }
            const decoder = new TextDecoder();
            while (true) {
                const { done, value } = await reader.read();
                if (done)
                    break;
                const chunk = decoder.decode(value);
                const lines = chunk.split('\n').filter(line => line.trim());
                for (const line of lines) {
                    if (line.startsWith('data: ')) {
                        const data = line.slice(6);
                        if (data === '[DONE]')
                            return;
                        try {
                            const parsed = JSON.parse(data);
                            const content = parsed.choices?.[0]?.delta?.content;
                            if (content) {
                                yield content;
                            }
                        }
                        catch {
                            // Skip invalid JSON
                        }
                    }
                }
            }
        }
        catch (error) {
            if (error instanceof Error) {
                throw error;
            }
            throw new Error(`Streaming failed: ${String(error)}`);
        }
    }
    /**
     * Get available models list
     */
    getAvailableModels() {
        return [...this.config.availableModels];
    }
    /**
     * Get default model
     */
    getDefaultModel() {
        return this.config.defaultModel;
    }
    /**
     * Change default model
     */
    setDefaultModel(model) {
        if (!this.config.availableModels.includes(model)) {
            throw new Error(`Model "${model}" not available`);
        }
        this.config.defaultModel = model;
    }
}
exports.NVIDIAAdapter = NVIDIAAdapter;
// Model metadata
exports.MODEL_METADATA = {
    'nvidia/moonshotai/kimi-k2.5': {
        name: 'Kimi K2.5',
        description: 'Long context, excellent for coding',
        bestFor: ['code generation', 'long context', 'documentation']
    },
    'nvidia/google/gemma-4-31b-it': {
        name: 'Gemma 4 31B',
        description: 'Balanced performance and efficiency',
        bestFor: ['general tasks', 'reasoning', 'chat']
    },
    'nvidia/deepseek-ai/deepseek-r1': {
        name: 'DeepSeek R1',
        description: 'Strong reasoning and chain-of-thought',
        bestFor: ['complex reasoning', 'architecture', 'planning']
    },
    'nvidia/mistralai/mixtral-8x22b-instruct-v0.1': {
        name: 'Mixtral 8x22B',
        description: 'MoE architecture, efficient',
        bestFor: ['parallel tasks', 'diverse skills', 'cost-effective']
    }
};
function getModelInfo(modelId) {
    return exports.MODEL_METADATA[modelId] || null;
}
//# sourceMappingURL=adapter.js.map