{"version":3,"file":"motorhead_memory.cjs","names":["fields: MotorheadMemoryInput","AsyncCaller","headers: HeadersInit","message: MotorheadMemoryMessage","_values: InputValues","result","inputValues: InputValues","outputValues: OutputValues"],"sources":["../../src/memory/motorhead_memory.ts"],"sourcesContent":["import {\n  InputValues,\n  OutputValues,\n  MemoryVariables,\n  getInputValue,\n  getOutputValue,\n} from \"@langchain/core/memory\";\nimport { getBufferString } from \"@langchain/core/messages\";\nimport {\n  AsyncCaller,\n  AsyncCallerParams,\n} from \"@langchain/core/utils/async_caller\";\nimport { BaseChatMemory, BaseChatMemoryInput } from \"./chat_memory.js\";\n\n/**\n * Interface for the structure of a memory message in the Motorhead\n * service. It includes the role and content of the message.\n */\nexport interface MotorheadMemoryMessage {\n  role: string;\n  content: string;\n}\n\n/**\n * @interface\n */\nexport type MotorheadMemoryInput = BaseChatMemoryInput &\n  AsyncCallerParams & {\n    sessionId: string;\n    url?: string;\n    memoryKey?: string;\n    timeout?: number;\n    apiKey?: string;\n    clientId?: string;\n  };\n\nconst MANAGED_URL = \"https://api.getmetal.io/v1/motorhead\";\n\n/**\n * Class for managing chat message memory using the Motorhead service. It\n * extends BaseChatMemory and includes methods for initializing the\n * memory, loading memory variables, and saving the context.\n */\nexport class MotorheadMemory extends BaseChatMemory {\n  url = MANAGED_URL;\n\n  timeout = 3000;\n\n  memoryKey = \"history\";\n\n  sessionId: string;\n\n  context?: string;\n\n  caller: AsyncCaller;\n\n  // Managed Params\n  apiKey?: string;\n\n  clientId?: string;\n\n  constructor(fields: MotorheadMemoryInput) {\n    const {\n      sessionId,\n      url,\n      memoryKey,\n      timeout,\n      returnMessages,\n      inputKey,\n      outputKey,\n      chatHistory,\n      apiKey,\n      clientId,\n      ...rest\n    } = fields;\n    super({ returnMessages, inputKey, outputKey, chatHistory });\n\n    this.caller = new AsyncCaller(rest);\n    this.sessionId = sessionId;\n    this.url = url ?? this.url;\n    this.memoryKey = memoryKey ?? this.memoryKey;\n    this.timeout = timeout ?? this.timeout;\n    this.apiKey = apiKey;\n    this.clientId = clientId;\n  }\n\n  get memoryKeys() {\n    return [this.memoryKey];\n  }\n\n  _getHeaders(): HeadersInit {\n    const isManaged = this.url === MANAGED_URL;\n\n    const headers: HeadersInit = {\n      \"Content-Type\": \"application/json\",\n    };\n\n    if (isManaged && !(this.apiKey && this.clientId)) {\n      throw new Error(\n        \"apiKey and clientId are required for managed motorhead. Visit https://getmetal.io to get your keys.\"\n      );\n    }\n\n    if (isManaged && this.apiKey && this.clientId) {\n      headers[\"x-metal-api-key\"] = this.apiKey;\n      headers[\"x-metal-client-id\"] = this.clientId;\n    }\n    return headers;\n  }\n\n  /**\n   * Method that initializes the memory by fetching the session memory from\n   * the Motorhead service. It adds the messages to the chat history and\n   * sets the context if it is not 'NONE'.\n   */\n  async init(): Promise<void> {\n    const res = await this.caller.call(\n      fetch,\n      `${this.url}/sessions/${this.sessionId}/memory`,\n      {\n        signal: this.timeout ? AbortSignal.timeout(this.timeout) : undefined,\n        headers: this._getHeaders(),\n      }\n    );\n\n    const json = await res.json();\n    const data = json?.data || json; // Managed Motorhead returns { data: { messages: [], context: \"NONE\" } }\n    const { messages = [], context = \"NONE\" } = data;\n\n    await Promise.all(\n      messages.reverse().map(async (message: MotorheadMemoryMessage) => {\n        if (message.role === \"AI\") {\n          await this.chatHistory.addAIChatMessage(message.content);\n        } else {\n          await this.chatHistory.addUserMessage(message.content);\n        }\n      })\n    );\n\n    if (context && context !== \"NONE\") {\n      this.context = context;\n    }\n  }\n\n  /**\n   * Method that loads the memory variables. It gets the chat messages and\n   * returns them as a string or an array based on the returnMessages flag.\n   * @param _values The input values.\n   * @returns A promise that resolves with the memory variables.\n   */\n  async loadMemoryVariables(_values: InputValues): Promise<MemoryVariables> {\n    const messages = await this.chatHistory.getMessages();\n    if (this.returnMessages) {\n      const result = {\n        [this.memoryKey]: messages,\n      };\n      return result;\n    }\n    const result = {\n      [this.memoryKey]: getBufferString(messages),\n    };\n    return result;\n  }\n\n  /**\n   * Method that saves the context to the Motorhead service and the base\n   * chat memory. It sends a POST request to the Motorhead service with the\n   * input and output messages, and calls the saveContext method of the base\n   * chat memory.\n   * @param inputValues The input values.\n   * @param outputValues The output values.\n   * @returns A promise that resolves when the context is saved.\n   */\n  async saveContext(\n    inputValues: InputValues,\n    outputValues: OutputValues\n  ): Promise<void> {\n    const input = getInputValue(inputValues, this.inputKey);\n    const output = getOutputValue(outputValues, this.outputKey);\n    await Promise.all([\n      this.caller.call(fetch, `${this.url}/sessions/${this.sessionId}/memory`, {\n        signal: this.timeout ? AbortSignal.timeout(this.timeout) : undefined,\n        method: \"POST\",\n        body: JSON.stringify({\n          messages: [\n            { role: \"Human\", content: `${input}` },\n            { role: \"AI\", content: `${output}` },\n          ],\n        }),\n        headers: this._getHeaders(),\n      }),\n      super.saveContext(inputValues, outputValues),\n    ]);\n  }\n}\n"],"mappings":";;;;;;;;;AAoCA,MAAM,cAAc;;;;;;AAOpB,IAAa,kBAAb,6DAAqC,eAAe;CAClD,MAAM;CAEN,UAAU;CAEV,YAAY;CAEZ;CAEA;CAEA;CAGA;CAEA;CAEA,YAAYA,QAA8B;EACxC,MAAM,EACJ,WACA,KACA,WACA,SACA,gBACA,UACA,WACA,aACA,QACA,SACA,GAAG,MACJ,GAAG;EACJ,MAAM;GAAE;GAAgB;GAAU;GAAW;EAAa,EAAC;EAE3D,KAAK,SAAS,IAAIC,gDAAY;EAC9B,KAAK,YAAY;EACjB,KAAK,MAAM,OAAO,KAAK;EACvB,KAAK,YAAY,aAAa,KAAK;EACnC,KAAK,UAAU,WAAW,KAAK;EAC/B,KAAK,SAAS;EACd,KAAK,WAAW;CACjB;CAED,IAAI,aAAa;AACf,SAAO,CAAC,KAAK,SAAU;CACxB;CAED,cAA2B;EACzB,MAAM,YAAY,KAAK,QAAQ;EAE/B,MAAMC,UAAuB,EAC3B,gBAAgB,mBACjB;AAED,MAAI,aAAa,EAAE,KAAK,UAAU,KAAK,UACrC,OAAM,IAAI,MACR;AAIJ,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