langchain.cjs 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. "use strict";
  2. Object.defineProperty(exports, "__esModule", { value: true });
  3. exports.getLangchainStringEvaluator = getLangchainStringEvaluator;
  4. // eslint-disable-next-line import/no-extraneous-dependencies
  5. const evaluation_1 = require("langchain/evaluation");
  6. const langchain_js_1 = require("../langchain.cjs");
  7. function isStringifiable(value) {
  8. return (typeof value === "string" ||
  9. typeof value === "number" ||
  10. typeof value === "boolean" ||
  11. typeof value === "bigint");
  12. }
  13. // utility methods for extracting stringified values
  14. // from unknown inputs and records
  15. function getPrimitiveValue(value) {
  16. if (isStringifiable(value))
  17. return String(value);
  18. if (!Array.isArray(value) && typeof value === "object" && value != null) {
  19. const values = Object.values(value);
  20. if (values.length === 1 && isStringifiable(values[0])) {
  21. return String(values[0]);
  22. }
  23. }
  24. return undefined;
  25. }
  26. /**
  27. * @deprecated Use `evaluate` instead.
  28. *
  29. * This utility function loads a LangChain string evaluator and returns a function
  30. * which can be used by newer `evaluate` function.
  31. *
  32. * @param type Type of string evaluator, one of "criteria" or "labeled_criteria
  33. * @param options Options for loading the evaluator
  34. * @returns Evaluator consumable by `evaluate`
  35. */
  36. async function getLangchainStringEvaluator(type, options) {
  37. const evaluator = await (0, evaluation_1.loadEvaluator)(type, options);
  38. const feedbackKey = getPrimitiveValue(options.criteria) ?? type;
  39. const formatEvaluatorInputs = options.formatEvaluatorInputs ??
  40. ((run, example) => {
  41. const prediction = getPrimitiveValue(run.outputs);
  42. const reference = getPrimitiveValue(example.outputs);
  43. const input = getPrimitiveValue(example.inputs);
  44. if (prediction == null)
  45. throw new Error("Missing prediction");
  46. if (type === "criteria")
  47. return { prediction, input };
  48. return { prediction, reference, input };
  49. });
  50. return async (run, example) => {
  51. const score = await evaluator.evaluateStrings(formatEvaluatorInputs(run, example), { callbacks: await (0, langchain_js_1.getLangchainCallbacks)() });
  52. return { key: feedbackKey, ...score };
  53. };
  54. }