memory.js 2.2 KB

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