var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
import { BaseCallbackHandler } from "@langchain/core/callbacks/base";
function isLangChainAgentCompletionAdapter(adapter) {
    return typeof adapter
        .getLangChainAgentSpec === "function";
}
function getAgentChatModelSpec(params) {
    return __awaiter(this, void 0, void 0, function* () {
        var _a;
        const spec = yield params.adapter.getLangChainAgentSpec({
            maxTokens: params.maxTokens,
            purpose: params.purpose,
        });
        return {
            model: spec.model,
            middleware: ((_a = spec.middleware) !== null && _a !== void 0 ? _a : []),
        };
    });
}
class AgentLlmMetricsLogger extends BaseCallbackHandler {
    constructor() {
        super(...arguments);
        this.name = "AgentLlmMetricsLogger";
        this.lc_prefer_streaming = true;
        this.pendingRuns = new Map();
    }
    handleLLMStart(_llm, _prompts, runId) {
        return __awaiter(this, void 0, void 0, function* () {
            this.pendingRuns.set(runId, { startedAt: Date.now() });
        });
    }
    handleLLMEnd(_output, runId) {
        return __awaiter(this, void 0, void 0, function* () {
            this.pendingRuns.delete(runId);
        });
    }
    handleLLMError(_error, runId) {
        return __awaiter(this, void 0, void 0, function* () {
            this.pendingRuns.delete(runId);
        });
    }
}
export function createAgentLlmMetricsLogger() {
    return new AgentLlmMetricsLogger();
}
export function createAgentChatModel(params) {
    return __awaiter(this, void 0, void 0, function* () {
        if (!isLangChainAgentCompletionAdapter(params.adapter)) {
            throw new Error("AdminForth Agent requires completionAdapter to implement getLangChainAgentSpec({ maxTokens, purpose }).");
        }
        return yield getAgentChatModelSpec({
            adapter: params.adapter,
            maxTokens: params.maxTokens,
            purpose: params.purpose,
        });
    });
}
