{"version":3,"file":"motorhead_memory.cjs","names":["AsyncCaller"],"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,cAAA,2BAAA,oBAAqC,eAAe;CAClD,MAAM;CAEN,UAAU;CAEV,YAAY;CAEZ;CAEA;CAEA;CAGA;CAEA;CAEA,YAAY,QAA8B;EACxC,MAAM,EACJ,WACA,KACA,WACA,SACA,gBACA,UACA,WACA,aACA,QACA,UACA,GAAG,SACD;AACJ,QAAM;GAAE;GAAgB;GAAU;GAAW;GAAa,CAAC;AAE3D,OAAK,SAAS,IAAIA,mCAAAA,YAAY,KAAK;AACnC,OAAK,YAAY;AACjB,OAAK,MAAM,OAAO,KAAK;AACvB,OAAK,YAAY,aAAa,KAAK;AACnC,OAAK,UAAU,WAAW,KAAK;AAC/B,OAAK,SAAS;AACd,OAAK,WAAW;;CAGlB,IAAI,aAAa;AACf,SAAO,CAAC,KAAK,UAAU;;CAGzB,cAA2B;EACzB,MAAM,YAAY,KAAK,QAAQ;EAE/B,MAAM,UAAuB,EAC3B,gBAAgB,oBACjB;AAED,MAAI,aAAa,EAAE,KAAK,UAAU,KAAK,UACrC,OAAM,IAAI,MACR,sGACD;AAGH,MAAI,aAAa,KAAK,UAAU,KAAK,UAAU;AAC7C,WAAQ,qBAAqB,KAAK;AAClC,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