"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.createOpenAIModel = void 0;
const tracer_langchain_1 = require("@langchain/core/tracers/tracer_langchain");
const openai_1 = require("@langchain/openai");
const langsmith_1 = require("langsmith");
const lodash_1 = require("lodash");
const constants_1 = require("./constants");
/**
 * Creates a configured OpenAI model instance with proper tracing metadata
 * Settings can optionally include openAiApiKey, otherwise falls back to environment configuration
 *
 * @param config - Configuration for model creation
 * @returns Configured model, metadata for tracing, and optional callbacks for hiding data
 * @throws Error if no API key is available in either settings or environment
 *
 * @example
 * ```typescript
 * const { model, metadata, callbacks } = await createOpenAIModel({
 *   settings,
 *   helpers,
 *   payload,
 *   modelType: OPENAI_MODELS.GPT4oMini,
 *   hideDataForTracing: true
 * })
 * ```
 */
const createOpenAIModel = async ({ settings = {}, helpers, payload, modelType = constants_1.OPENAI_MODELS.GPT4oMini, hideDataForTracing = false, }) => {
    var _a, _b, _c, _d, _e, _f, _g;
    const apiKey = (_a = settings.openAiApiKey) !== null && _a !== void 0 ? _a : helpers.getOpenAIConfig().apiKey;
    if ((0, lodash_1.isNil)(apiKey)) {
        throw new Error('No OpenAI API key available in settings or environment configuration');
    }
    const model = new openai_1.ChatOpenAI({
        modelName: constants_1.MODEL_VERSIONS[modelType],
        openAIApiKey: apiKey,
        ...(0, constants_1.getDefaultConfig)(modelType),
    });
    let callbacks;
    if (hideDataForTracing) {
        // Utility function to mask outputs while preserving token usage
        const maskOutputs = (outputs) => {
            var _a;
            const maskedGenerations = outputs.generations.map((generationArray) => generationArray.map((generation) => {
                var _a, _b, _c, _d, _e, _f;
                return ({
                    text: '[MASKED]',
                    message: {
                        lc: 1,
                        type: 'constructor',
                        id: ['langchain_core', 'messages', 'AIMessage'],
                        kwargs: {
                            content: '[MASKED]',
                            response_metadata: {
                                tokenUsage: (_c = (_b = (_a = generation.message) === null || _a === void 0 ? void 0 : _a.kwargs) === null || _b === void 0 ? void 0 : _b.response_metadata) === null || _c === void 0 ? void 0 : _c.tokenUsage,
                                finish_reason: (_f = (_e = (_d = generation.message) === null || _d === void 0 ? void 0 : _d.kwargs) === null || _e === void 0 ? void 0 : _e.response_metadata) === null || _f === void 0 ? void 0 : _f.finish_reason,
                            },
                        },
                    },
                });
            }));
            return {
                generations: maskedGenerations,
                llmOutput: {
                    tokenUsage: (_a = outputs.llmOutput) === null || _a === void 0 ? void 0 : _a.tokenUsage,
                },
            };
        };
        const client = new langsmith_1.Client({
            hideInputs: () => ({}),
            hideOutputs: maskOutputs,
        });
        callbacks = [new tracer_langchain_1.LangChainTracer({ client })];
    }
    return {
        model,
        metadata: {
            activity_id: (_b = payload.activity.id) !== null && _b !== void 0 ? _b : '',
            tenant_id: (_c = payload.pathway.tenant_id) !== null && _c !== void 0 ? _c : '',
            care_flow_definition_id: (_d = payload.pathway.definition_id) !== null && _d !== void 0 ? _d : '',
            care_flow_id: (_e = payload.pathway.id) !== null && _e !== void 0 ? _e : '',
            org_slug: (_f = payload.pathway.org_slug) !== null && _f !== void 0 ? _f : '',
            org_id: (_g = payload.pathway.org_id) !== null && _g !== void 0 ? _g : '',
        },
        callbacks, // if not hideDataForTracing, callbacks is undefined, will use default callbacks
    };
};
exports.createOpenAIModel = createOpenAIModel;
//# sourceMappingURL=createOpenAIModel.js.map