langchain.js 2.1 KB

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