"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.callAgentExecutor = void 0;
var _agents = require("langchain/agents");
var _chains = require("langchain/chains");
var _memory = require("langchain/memory");
var _tools = require("langchain/tools");
var _elasticsearch_store = require("../elasticsearch_store/elasticsearch_store");
var _actions_client_llm = require("../llm/actions_client_llm");
var _constants = require("../../../routes/knowledge_base/constants");
/*
 * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
 * or more contributor license agreements. Licensed under the Elastic License
 * 2.0; you may not use this file except in compliance with the Elastic License
 * 2.0.
 */

const callAgentExecutor = async ({
  actions,
  connectorId,
  esClient,
  langChainMessages,
  llmType,
  logger,
  request,
  elserId,
  kbResource
}) => {
  const llm = new _actions_client_llm.ActionsClientLlm({
    actions,
    connectorId,
    request,
    llmType,
    logger
  });
  const pastMessages = langChainMessages.slice(0, -1); // all but the last message
  const latestMessage = langChainMessages.slice(-1); // the last message

  const memory = new _memory.BufferMemory({
    chatHistory: new _memory.ChatMessageHistory(pastMessages),
    memoryKey: 'chat_history',
    // this is the key expected by https://github.com/langchain-ai/langchainjs/blob/a13a8969345b0f149c1ca4a120d63508b06c52a5/langchain/src/agents/initialize.ts#L166
    inputKey: 'input',
    outputKey: 'output',
    returnMessages: true
  });

  // ELSER backed ElasticsearchStore for Knowledge Base
  const esStore = new _elasticsearch_store.ElasticsearchStore(esClient, _constants.KNOWLEDGE_BASE_INDEX_PATTERN, logger, elserId, kbResource);
  const modelExists = await esStore.isModelInstalled();
  if (!modelExists) {
    throw new Error('Please ensure ELSER is configured to use the Knowledge Base, otherwise disable the Knowledge Base in Advanced Settings to continue.');
  }

  // Create a chain that uses the ELSER backed ElasticsearchStore, override k=10 for esql query generation for now
  const chain = _chains.RetrievalQAChain.fromLLM(llm, esStore.asRetriever(10));
  const tools = [new _tools.ChainTool({
    name: 'esql-language-knowledge-base',
    description: 'Call this for knowledge on how to build an ESQL query, or answer questions about the ES|QL query language.',
    chain
  })];
  const executor = await (0, _agents.initializeAgentExecutorWithOptions)(tools, llm, {
    agentType: 'chat-conversational-react-description',
    memory,
    verbose: false
  });
  await executor.call({
    input: latestMessage[0].content
  });
  return {
    connector_id: connectorId,
    data: llm.getActionResultData(),
    // the response from the actions framework
    status: 'ok'
  };
};
exports.callAgentExecutor = callAgentExecutor;