memory.cjs 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. "use strict";
  2. Object.defineProperty(exports, "__esModule", { value: true });
  3. exports.getPromptInputKey = exports.getOutputValue = exports.getInputValue = exports.BaseMemory = void 0;
  4. /**
  5. * Abstract base class for memory in LangChain's Chains. Memory refers to
  6. * the state in Chains. It can be used to store information about past
  7. * executions of a Chain and inject that information into the inputs of
  8. * future executions of the Chain.
  9. */
  10. class BaseMemory {
  11. }
  12. exports.BaseMemory = BaseMemory;
  13. const getValue = (values, key) => {
  14. if (key !== undefined) {
  15. return values[key];
  16. }
  17. const keys = Object.keys(values);
  18. if (keys.length === 1) {
  19. return values[keys[0]];
  20. }
  21. };
  22. /**
  23. * This function is used by memory classes to select the input value
  24. * to use for the memory. If there is only one input value, it is used.
  25. * If there are multiple input values, the inputKey must be specified.
  26. */
  27. const getInputValue = (inputValues, inputKey) => {
  28. const value = getValue(inputValues, inputKey);
  29. if (!value) {
  30. const keys = Object.keys(inputValues);
  31. throw new Error(`input values have ${keys.length} keys, you must specify an input key or pass only 1 key as input`);
  32. }
  33. return value;
  34. };
  35. exports.getInputValue = getInputValue;
  36. /**
  37. * This function is used by memory classes to select the output value
  38. * to use for the memory. If there is only one output value, it is used.
  39. * If there are multiple output values, the outputKey must be specified.
  40. * If no outputKey is specified, an error is thrown.
  41. */
  42. const getOutputValue = (outputValues, outputKey) => {
  43. const value = getValue(outputValues, outputKey);
  44. if (!value && value !== "") {
  45. const keys = Object.keys(outputValues);
  46. throw new Error(`output values have ${keys.length} keys, you must specify an output key or pass only 1 key as output`);
  47. }
  48. return value;
  49. };
  50. exports.getOutputValue = getOutputValue;
  51. /**
  52. * Function used by memory classes to get the key of the prompt input,
  53. * excluding any keys that are memory variables or the "stop" key. If
  54. * there is not exactly one prompt input key, an error is thrown.
  55. */
  56. function getPromptInputKey(inputs, memoryVariables) {
  57. const promptInputKeys = Object.keys(inputs).filter((key) => !memoryVariables.includes(key) && key !== "stop");
  58. if (promptInputKeys.length !== 1) {
  59. throw new Error(`One input key expected, but got ${promptInputKeys.length}`);
  60. }
  61. return promptInputKeys[0];
  62. }
  63. exports.getPromptInputKey = getPromptInputKey;