/*
 * Copyright OpenSearch Contributors
 * SPDX-License-Identifier: Apache-2.0
 */
import { BaseConnector } from '../../../services/connectors/base/BaseConnector.js';
/**
 * OpenAI-compatible connector
 */
export class OpenAICompatibleConnector extends BaseConnector {
    constructor() {
        super(...arguments);
        this.type = 'openai-compatible';
        this.name = 'OpenAI-compatible';
        this.traceContext = { propagateHeader: true };
        this.supportsStreaming = false;
    }
    /**
     * Build OpenAI Chat Completion payload from test case
     */
    buildPayload(request) {
        const messages = [];
        // Add context as system message if present
        if (request.testCase.context && request.testCase.context.length > 0) {
            const contextText = request.testCase.context
                .map((c) => typeof c === 'string' ? c : JSON.stringify(c))
                .join('\n');
            messages.push({
                role: 'system',
                content: contextText,
            });
        }
        // Add the prompt as user message
        messages.push({
            role: 'user',
            content: request.testCase.initialPrompt,
        });
        const payload = {
            model: request.modelId,
            messages,
        };
        // Add tools if the test case defines them
        if (request.testCase.tools && request.testCase.tools.length > 0) {
            payload.tools = request.testCase.tools.map((tool) => ({
                type: 'function',
                function: {
                    name: tool.name,
                    description: tool.description || '',
                    parameters: tool.parameters || {},
                },
            }));
        }
        return payload;
    }
    /**
     * Execute OpenAI-compatible Chat Completion request
     */
    async execute(endpoint, request, auth, onProgress, onRawEvent) {
        const payload = request.payload || this.buildPayload(request);
        const headers = this.buildAuthHeaders(auth);
        this.injectTraceparentHeaders(headers);
        this.debug('Executing OpenAI-compatible request');
        this.debug('Endpoint:', endpoint);
        this.debug('Model:', payload.model);
        const response = await fetch(endpoint, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                ...headers,
            },
            body: JSON.stringify(payload),
        });
        if (!response.ok) {
            const errorText = await response.text();
            throw new Error(`OpenAI-compatible request failed: ${response.status} - ${errorText}`);
        }
        const data = await response.json();
        onRawEvent?.(data);
        const trajectory = this.parseResponse(data);
        trajectory.forEach(step => onProgress?.(step));
        return {
            trajectory,
            runId: data.id || null,
            rawEvents: [data],
            metadata: {
                model: data.model,
                usage: data.usage,
                finishReason: data.choices?.[0]?.finish_reason,
            },
        };
    }
    /**
     * Parse OpenAI Chat Completion response into trajectory steps
     */
    parseResponse(data) {
        const steps = [];
        const choice = data.choices?.[0];
        if (!choice) {
            steps.push(this.createStep('response', JSON.stringify(data, null, 2)));
            return steps;
        }
        const message = choice.message;
        // Handle tool calls
        if (message.tool_calls && message.tool_calls.length > 0) {
            for (const toolCall of message.tool_calls) {
                let toolArgs;
                try {
                    toolArgs = JSON.parse(toolCall.function.arguments);
                }
                catch {
                    toolArgs = toolCall.function.arguments;
                }
                steps.push(this.createStep('action', `Calling ${toolCall.function.name}...`, {
                    toolName: toolCall.function.name,
                    toolArgs,
                }));
            }
        }
        // Handle content response
        if (message.content) {
            steps.push(this.createStep('response', message.content));
        }
        // If no content and no tool calls, create a generic response
        if (steps.length === 0) {
            steps.push(this.createStep('response', '(empty response)'));
        }
        return steps;
    }
}
/**
 * Default instance for convenience
 */
export const openaiCompatibleConnector = new OpenAICompatibleConnector();
//# sourceMappingURL=OpenAICompatibleConnector.js.map