langchain 0.0.146 → 0.0.148

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (168) hide show
  1. package/chat_models/googlevertexai/web.cjs +1 -0
  2. package/chat_models/googlevertexai/web.d.ts +1 -0
  3. package/chat_models/googlevertexai/web.js +1 -0
  4. package/chat_models/googlevertexai.cjs +1 -1
  5. package/chat_models/googlevertexai.d.ts +1 -1
  6. package/chat_models/googlevertexai.js +1 -1
  7. package/dist/base_language/index.cjs +2 -2
  8. package/dist/base_language/index.d.ts +2 -1
  9. package/dist/base_language/index.js +1 -1
  10. package/dist/chains/base.d.ts +1 -1
  11. package/dist/chains/constitutional_ai/constitutional_principle.cjs +272 -1
  12. package/dist/chains/constitutional_ai/constitutional_principle.js +272 -1
  13. package/dist/chains/openai_functions/openapi.cjs +32 -27
  14. package/dist/chains/openai_functions/openapi.d.ts +9 -0
  15. package/dist/chains/openai_functions/openapi.js +31 -27
  16. package/dist/chat_models/base.d.ts +1 -1
  17. package/dist/chat_models/{googlevertexai.cjs → googlevertexai/common.cjs} +14 -26
  18. package/dist/chat_models/{googlevertexai.d.ts → googlevertexai/common.d.ts} +13 -22
  19. package/dist/chat_models/{googlevertexai.js → googlevertexai/common.js} +12 -24
  20. package/dist/chat_models/googlevertexai/index.cjs +36 -0
  21. package/dist/chat_models/googlevertexai/index.d.ts +21 -0
  22. package/dist/chat_models/googlevertexai/index.js +31 -0
  23. package/dist/chat_models/googlevertexai/web.cjs +33 -0
  24. package/dist/chat_models/googlevertexai/web.d.ts +19 -0
  25. package/dist/chat_models/googlevertexai/web.js +28 -0
  26. package/dist/chat_models/openai.cjs +1 -1
  27. package/dist/chat_models/openai.js +1 -1
  28. package/dist/document_loaders/web/notionapi.cjs +93 -70
  29. package/dist/document_loaders/web/notionapi.d.ts +33 -1
  30. package/dist/document_loaders/web/notionapi.js +89 -71
  31. package/dist/embeddings/googlevertexai.cjs +5 -1
  32. package/dist/embeddings/googlevertexai.d.ts +2 -1
  33. package/dist/embeddings/googlevertexai.js +5 -1
  34. package/dist/evaluation/agents/index.cjs +17 -0
  35. package/dist/evaluation/agents/index.d.ts +1 -0
  36. package/dist/evaluation/agents/index.js +1 -0
  37. package/dist/evaluation/agents/prompt.cjs +132 -0
  38. package/dist/evaluation/agents/prompt.d.ts +6 -0
  39. package/dist/evaluation/agents/prompt.js +129 -0
  40. package/dist/evaluation/agents/trajectory.cjs +189 -0
  41. package/dist/evaluation/agents/trajectory.d.ts +54 -0
  42. package/dist/evaluation/agents/trajectory.js +184 -0
  43. package/dist/evaluation/base.cjs +274 -0
  44. package/dist/evaluation/base.d.ts +232 -0
  45. package/dist/evaluation/base.js +263 -0
  46. package/dist/evaluation/comparison/index.cjs +17 -0
  47. package/dist/evaluation/comparison/index.d.ts +1 -0
  48. package/dist/evaluation/comparison/index.js +1 -0
  49. package/dist/evaluation/comparison/pairwise.cjs +244 -0
  50. package/dist/evaluation/comparison/pairwise.d.ts +50 -0
  51. package/dist/evaluation/comparison/pairwise.js +238 -0
  52. package/dist/evaluation/comparison/prompt.cjs +74 -0
  53. package/dist/evaluation/comparison/prompt.d.ts +21 -0
  54. package/dist/evaluation/comparison/prompt.js +71 -0
  55. package/dist/evaluation/criteria/criteria.cjs +259 -0
  56. package/dist/evaluation/criteria/criteria.d.ts +73 -0
  57. package/dist/evaluation/criteria/criteria.js +253 -0
  58. package/dist/evaluation/criteria/index.cjs +17 -0
  59. package/dist/evaluation/criteria/index.d.ts +1 -0
  60. package/dist/evaluation/criteria/index.js +1 -0
  61. package/dist/evaluation/criteria/prompt.cjs +36 -0
  62. package/dist/evaluation/criteria/prompt.d.ts +12 -0
  63. package/dist/evaluation/criteria/prompt.js +33 -0
  64. package/dist/evaluation/embedding_distance/base.cjs +163 -0
  65. package/dist/evaluation/embedding_distance/base.d.ts +78 -0
  66. package/dist/evaluation/embedding_distance/base.js +156 -0
  67. package/dist/evaluation/embedding_distance/index.cjs +17 -0
  68. package/dist/evaluation/embedding_distance/index.d.ts +1 -0
  69. package/dist/evaluation/embedding_distance/index.js +1 -0
  70. package/dist/evaluation/index.cjs +6 -0
  71. package/dist/evaluation/index.d.ts +6 -0
  72. package/dist/evaluation/index.js +6 -0
  73. package/dist/evaluation/loader.cjs +60 -0
  74. package/dist/evaluation/loader.d.ts +27 -0
  75. package/dist/evaluation/loader.js +56 -0
  76. package/dist/evaluation/types.cjs +2 -0
  77. package/dist/evaluation/types.d.ts +35 -0
  78. package/dist/evaluation/types.js +1 -0
  79. package/dist/experimental/llms/bittensor.cjs +141 -0
  80. package/dist/experimental/llms/bittensor.d.ts +33 -0
  81. package/dist/experimental/llms/bittensor.js +137 -0
  82. package/dist/experimental/multimodal_embeddings/googlevertexai.cjs +5 -1
  83. package/dist/experimental/multimodal_embeddings/googlevertexai.d.ts +2 -1
  84. package/dist/experimental/multimodal_embeddings/googlevertexai.js +5 -1
  85. package/dist/hub.d.ts +1 -1
  86. package/dist/llms/base.d.ts +1 -1
  87. package/dist/llms/{googlevertexai.js → googlevertexai/common.cjs} +21 -17
  88. package/dist/llms/{googlevertexai.d.ts → googlevertexai/common.d.ts} +13 -23
  89. package/dist/llms/{googlevertexai.cjs → googlevertexai/common.js} +17 -21
  90. package/dist/llms/googlevertexai/index.cjs +34 -0
  91. package/dist/llms/googlevertexai/index.d.ts +26 -0
  92. package/dist/llms/googlevertexai/index.js +30 -0
  93. package/dist/llms/googlevertexai/web.cjs +31 -0
  94. package/dist/llms/googlevertexai/web.d.ts +24 -0
  95. package/dist/llms/googlevertexai/web.js +27 -0
  96. package/dist/llms/openai-chat.cjs +1 -1
  97. package/dist/llms/openai-chat.js +1 -1
  98. package/dist/llms/openai.cjs +1 -1
  99. package/dist/llms/openai.js +1 -1
  100. package/dist/load/import_constants.cjs +3 -0
  101. package/dist/load/import_constants.js +3 -0
  102. package/dist/load/import_map.cjs +3 -2
  103. package/dist/load/import_map.d.ts +2 -1
  104. package/dist/load/import_map.js +2 -1
  105. package/dist/load/index.cjs +2 -1
  106. package/dist/load/index.js +2 -1
  107. package/dist/load/serializable.cjs +23 -4
  108. package/dist/load/serializable.js +23 -4
  109. package/dist/prompts/base.cjs +2 -2
  110. package/dist/prompts/base.d.ts +1 -1
  111. package/dist/prompts/base.js +1 -1
  112. package/dist/prompts/chat.cjs +2 -2
  113. package/dist/prompts/chat.d.ts +1 -1
  114. package/dist/prompts/chat.js +1 -1
  115. package/dist/retrievers/multi_query.cjs +140 -0
  116. package/dist/retrievers/multi_query.d.ts +33 -0
  117. package/dist/retrievers/multi_query.js +136 -0
  118. package/dist/schema/document.cjs +2 -2
  119. package/dist/schema/document.d.ts +1 -1
  120. package/dist/schema/document.js +1 -1
  121. package/dist/schema/output_parser.cjs +2 -2
  122. package/dist/schema/output_parser.d.ts +2 -1
  123. package/dist/schema/output_parser.js +1 -1
  124. package/dist/schema/retriever.cjs +2 -2
  125. package/dist/schema/retriever.d.ts +2 -1
  126. package/dist/schema/retriever.js +1 -1
  127. package/dist/schema/runnable/config.cjs +8 -0
  128. package/dist/schema/runnable/config.d.ts +3 -0
  129. package/dist/schema/runnable/config.js +4 -0
  130. package/dist/schema/{runnable.cjs → runnable/index.cjs} +290 -101
  131. package/dist/schema/{runnable.d.ts → runnable/index.d.ts} +127 -41
  132. package/dist/schema/{runnable.js → runnable/index.js} +284 -99
  133. package/dist/tools/base.d.ts +1 -1
  134. package/dist/types/googlevertexai-types.d.ts +11 -4
  135. package/dist/util/async_caller.cjs +35 -25
  136. package/dist/util/async_caller.d.ts +8 -0
  137. package/dist/util/async_caller.js +35 -25
  138. package/dist/util/googlevertexai-connection.cjs +14 -15
  139. package/dist/util/googlevertexai-connection.d.ts +7 -7
  140. package/dist/util/googlevertexai-connection.js +14 -15
  141. package/dist/util/googlevertexai-webauth.cjs +56 -0
  142. package/dist/util/googlevertexai-webauth.d.ts +25 -0
  143. package/dist/util/googlevertexai-webauth.js +52 -0
  144. package/dist/vectorstores/googlevertexai.cjs +9 -8
  145. package/dist/vectorstores/googlevertexai.d.ts +8 -7
  146. package/dist/vectorstores/googlevertexai.js +9 -8
  147. package/dist/vectorstores/pinecone.cjs +30 -22
  148. package/dist/vectorstores/pinecone.d.ts +3 -1
  149. package/dist/vectorstores/pinecone.js +30 -22
  150. package/dist/vectorstores/vectara.cjs +20 -23
  151. package/dist/vectorstores/vectara.d.ts +9 -2
  152. package/dist/vectorstores/vectara.js +20 -23
  153. package/experimental/llms/bittensor.cjs +1 -0
  154. package/experimental/llms/bittensor.d.ts +1 -0
  155. package/experimental/llms/bittensor.js +1 -0
  156. package/llms/googlevertexai/web.cjs +1 -0
  157. package/llms/googlevertexai/web.d.ts +1 -0
  158. package/llms/googlevertexai/web.js +1 -0
  159. package/llms/googlevertexai.cjs +1 -1
  160. package/llms/googlevertexai.d.ts +1 -1
  161. package/llms/googlevertexai.js +1 -1
  162. package/package.json +40 -3
  163. package/retrievers/multi_query.cjs +1 -0
  164. package/retrievers/multi_query.d.ts +1 -0
  165. package/retrievers/multi_query.js +1 -0
  166. package/schema/runnable.cjs +1 -1
  167. package/schema/runnable.d.ts +1 -1
  168. package/schema/runnable.js +1 -1
@@ -0,0 +1,189 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.TrajectoryEvalChain = exports.TrajectoryOutputParser = void 0;
4
+ const output_parser_js_1 = require("../../schema/output_parser.cjs");
5
+ const base_js_1 = require("../base.cjs");
6
+ const index_js_1 = require("../../schema/index.cjs");
7
+ const prompt_js_1 = require("./prompt.cjs");
8
+ /**
9
+ * A parser for the output of the TrajectoryEvalChain.
10
+ */
11
+ class TrajectoryOutputParser extends output_parser_js_1.BaseLLMOutputParser {
12
+ constructor() {
13
+ super(...arguments);
14
+ Object.defineProperty(this, "lc_namespace", {
15
+ enumerable: true,
16
+ configurable: true,
17
+ writable: true,
18
+ value: ["langchain", "evaluation", "agents"]
19
+ });
20
+ }
21
+ static lc_name() {
22
+ return "TrajectoryOutputParser";
23
+ }
24
+ parseResult(generations, _callbacks) {
25
+ const { text } = generations[0];
26
+ if (!text.includes("Score:")) {
27
+ throw new Error(`Could not find score in model eval output: ${text}`);
28
+ }
29
+ let [reasoning, scoreStr] = text.split("Score:", 2);
30
+ reasoning = reasoning.trim();
31
+ scoreStr = scoreStr.trim();
32
+ // Use regex to extract the score.
33
+ // This will get the number in the string, even if it is a float or more than 10.
34
+ // E.g. "Score: 1" will return 1, "Score: 3.5" will return 3.5, and
35
+ // "Score: 10" will return 10.
36
+ // The score should be an integer digit in the range 1-5.
37
+ const scoreMatch = scoreStr.match(/(\d+(\.\d+)?)/);
38
+ if (scoreMatch === null || scoreMatch[1].includes(".")) {
39
+ throw new Error(`Score is not an integer digit in the range 1-5: ${text}`);
40
+ }
41
+ const score = +scoreMatch[1];
42
+ if (score < 1 || score > 5) {
43
+ throw new Error(`Score is not a digit in the range 1-5: ${text}`);
44
+ }
45
+ const normalizedScore = (score - 1) / 4;
46
+ return Promise.resolve({
47
+ reasoning,
48
+ score: normalizedScore,
49
+ });
50
+ }
51
+ }
52
+ exports.TrajectoryOutputParser = TrajectoryOutputParser;
53
+ /**
54
+ * A chain for evaluating ReAct style agents.
55
+ *
56
+ * This chain is used to evaluate ReAct style agents by reasoning about
57
+ * the sequence of actions taken and their outcomes.
58
+ */
59
+ class TrajectoryEvalChain extends base_js_1.AgentTrajectoryEvaluator {
60
+ constructor() {
61
+ super(...arguments);
62
+ Object.defineProperty(this, "criterionName", {
63
+ enumerable: true,
64
+ configurable: true,
65
+ writable: true,
66
+ value: void 0
67
+ });
68
+ Object.defineProperty(this, "evaluationName", {
69
+ enumerable: true,
70
+ configurable: true,
71
+ writable: true,
72
+ value: this.criterionName
73
+ });
74
+ Object.defineProperty(this, "requiresInput", {
75
+ enumerable: true,
76
+ configurable: true,
77
+ writable: true,
78
+ value: true
79
+ });
80
+ Object.defineProperty(this, "requiresReference", {
81
+ enumerable: true,
82
+ configurable: true,
83
+ writable: true,
84
+ value: false
85
+ });
86
+ Object.defineProperty(this, "outputParser", {
87
+ enumerable: true,
88
+ configurable: true,
89
+ writable: true,
90
+ value: new TrajectoryOutputParser()
91
+ });
92
+ }
93
+ static lc_name() {
94
+ return "TrajectoryEvalChain";
95
+ }
96
+ static resolveTrajectoryPrompt(prompt, agentTools) {
97
+ let _prompt;
98
+ if (prompt) {
99
+ _prompt = prompt;
100
+ }
101
+ else if (agentTools) {
102
+ _prompt = prompt_js_1.EVAL_CHAT_PROMPT;
103
+ }
104
+ else {
105
+ _prompt = prompt_js_1.TOOL_FREE_EVAL_CHAT_PROMPT;
106
+ }
107
+ return _prompt;
108
+ }
109
+ /**
110
+ * Get the description of the agent tools.
111
+ *
112
+ * @returns The description of the agent tools.
113
+ */
114
+ static toolsDescription(agentTools) {
115
+ return agentTools
116
+ .map((tool, i) => `Tool ${i + 1}: ${tool.name}\n Description: ${tool.description}`)
117
+ .join("\n\n");
118
+ }
119
+ /**
120
+ * Create a new TrajectoryEvalChain.
121
+ * @param llm
122
+ * @param agentTools - The tools used by the agent.
123
+ * @param chainOptions - The options for the chain.
124
+ */
125
+ static async fromLLM(llm, agentTools, chainOptions) {
126
+ let prompt = this.resolveTrajectoryPrompt(chainOptions?.prompt, agentTools);
127
+ if (agentTools) {
128
+ const toolDescriptions = this.toolsDescription(agentTools);
129
+ prompt = await prompt.partial({ toolDescriptions });
130
+ }
131
+ const options = chainOptions;
132
+ if (options) {
133
+ // remove prompt from chainOptions
134
+ delete options.prompt;
135
+ }
136
+ return new this({
137
+ llm,
138
+ prompt,
139
+ ...options,
140
+ });
141
+ }
142
+ _prepareOutput(result) {
143
+ const parsed = result[this.outputKey];
144
+ if (index_js_1.RUN_KEY in result && result[index_js_1.RUN_KEY]) {
145
+ parsed[index_js_1.RUN_KEY] = result[index_js_1.RUN_KEY];
146
+ }
147
+ return parsed;
148
+ }
149
+ /**
150
+ * Get the agent trajectory as a formatted string.
151
+ *
152
+ * @param steps - The agent trajectory.
153
+ * @returns The formatted agent trajectory.
154
+ */
155
+ getAgentTrajectory(steps) {
156
+ return steps
157
+ .map((step, i) => {
158
+ const { action, observation } = step;
159
+ return (`Step ${i + 1}:\n` +
160
+ `Tool used: ${action.tool}\n` +
161
+ `Tool input: ${action.toolInput}\n` +
162
+ `Tool output: ${observation}`);
163
+ })
164
+ .join("\n\n");
165
+ }
166
+ formatReference(reference) {
167
+ if (!reference) {
168
+ return "";
169
+ }
170
+ return `
171
+ The following is the expected answer. Use this to measure correctness:
172
+ [GROUND_TRUTH]
173
+ ${reference}
174
+ [END_GROUND_TRUTH]
175
+ `;
176
+ }
177
+ async _evaluateAgentTrajectory(args, callOptions, config) {
178
+ const { input, prediction, reference, agentTrajectory } = args;
179
+ const inputs = {
180
+ question: input,
181
+ agentTrajectory: this.getAgentTrajectory(agentTrajectory),
182
+ answer: prediction,
183
+ reference: this.formatReference(reference),
184
+ };
185
+ const result = await this.call({ ...inputs, ...callOptions }, config);
186
+ return this._prepareOutput(result);
187
+ }
188
+ }
189
+ exports.TrajectoryEvalChain = TrajectoryEvalChain;
@@ -0,0 +1,54 @@
1
+ import { BaseLLMOutputParser } from "../../schema/output_parser.js";
2
+ import { AgentTrajectoryEvaluator, EvalOutputType, LLMEvalChainInput, LLMTrajectoryEvaluatorArgs } from "../base.js";
3
+ import { AgentStep, ChainValues, ChatGeneration, Generation } from "../../schema/index.js";
4
+ import { Callbacks } from "../../callbacks/index.js";
5
+ import { BaseCallbackConfig } from "../../callbacks/manager.js";
6
+ import { BasePromptTemplate } from "../../prompts/index.js";
7
+ import { StructuredTool } from "../../tools/index.js";
8
+ import { BaseChatModel } from "../../chat_models/base.js";
9
+ /**
10
+ * A parser for the output of the TrajectoryEvalChain.
11
+ */
12
+ export declare class TrajectoryOutputParser extends BaseLLMOutputParser<EvalOutputType> {
13
+ static lc_name(): string;
14
+ lc_namespace: string[];
15
+ parseResult(generations: Generation[] | ChatGeneration[], _callbacks: Callbacks | undefined): Promise<EvalOutputType>;
16
+ }
17
+ /**
18
+ * A chain for evaluating ReAct style agents.
19
+ *
20
+ * This chain is used to evaluate ReAct style agents by reasoning about
21
+ * the sequence of actions taken and their outcomes.
22
+ */
23
+ export declare class TrajectoryEvalChain extends AgentTrajectoryEvaluator {
24
+ static lc_name(): string;
25
+ criterionName?: string;
26
+ evaluationName?: string;
27
+ requiresInput: boolean;
28
+ requiresReference: boolean;
29
+ outputParser: TrajectoryOutputParser;
30
+ static resolveTrajectoryPrompt(prompt?: BasePromptTemplate | undefined, agentTools?: StructuredTool[]): import("../../prompts/chat.js").ChatPromptTemplate<any, any> | BasePromptTemplate<any, import("../../schema/index.js").BasePromptValue, any>;
31
+ /**
32
+ * Get the description of the agent tools.
33
+ *
34
+ * @returns The description of the agent tools.
35
+ */
36
+ static toolsDescription(agentTools: StructuredTool[]): string;
37
+ /**
38
+ * Create a new TrajectoryEvalChain.
39
+ * @param llm
40
+ * @param agentTools - The tools used by the agent.
41
+ * @param chainOptions - The options for the chain.
42
+ */
43
+ static fromLLM(llm: BaseChatModel, agentTools?: StructuredTool[], chainOptions?: Partial<Omit<LLMEvalChainInput, "llm">>): Promise<TrajectoryEvalChain>;
44
+ _prepareOutput(result: ChainValues): any;
45
+ /**
46
+ * Get the agent trajectory as a formatted string.
47
+ *
48
+ * @param steps - The agent trajectory.
49
+ * @returns The formatted agent trajectory.
50
+ */
51
+ getAgentTrajectory(steps: AgentStep[]): string;
52
+ formatReference(reference?: string): string;
53
+ _evaluateAgentTrajectory(args: LLMTrajectoryEvaluatorArgs, callOptions: this["llm"]["CallOptions"], config?: Callbacks | BaseCallbackConfig): Promise<ChainValues>;
54
+ }
@@ -0,0 +1,184 @@
1
+ import { BaseLLMOutputParser } from "../../schema/output_parser.js";
2
+ import { AgentTrajectoryEvaluator, } from "../base.js";
3
+ import { RUN_KEY, } from "../../schema/index.js";
4
+ import { EVAL_CHAT_PROMPT, TOOL_FREE_EVAL_CHAT_PROMPT } from "./prompt.js";
5
+ /**
6
+ * A parser for the output of the TrajectoryEvalChain.
7
+ */
8
+ export class TrajectoryOutputParser extends BaseLLMOutputParser {
9
+ constructor() {
10
+ super(...arguments);
11
+ Object.defineProperty(this, "lc_namespace", {
12
+ enumerable: true,
13
+ configurable: true,
14
+ writable: true,
15
+ value: ["langchain", "evaluation", "agents"]
16
+ });
17
+ }
18
+ static lc_name() {
19
+ return "TrajectoryOutputParser";
20
+ }
21
+ parseResult(generations, _callbacks) {
22
+ const { text } = generations[0];
23
+ if (!text.includes("Score:")) {
24
+ throw new Error(`Could not find score in model eval output: ${text}`);
25
+ }
26
+ let [reasoning, scoreStr] = text.split("Score:", 2);
27
+ reasoning = reasoning.trim();
28
+ scoreStr = scoreStr.trim();
29
+ // Use regex to extract the score.
30
+ // This will get the number in the string, even if it is a float or more than 10.
31
+ // E.g. "Score: 1" will return 1, "Score: 3.5" will return 3.5, and
32
+ // "Score: 10" will return 10.
33
+ // The score should be an integer digit in the range 1-5.
34
+ const scoreMatch = scoreStr.match(/(\d+(\.\d+)?)/);
35
+ if (scoreMatch === null || scoreMatch[1].includes(".")) {
36
+ throw new Error(`Score is not an integer digit in the range 1-5: ${text}`);
37
+ }
38
+ const score = +scoreMatch[1];
39
+ if (score < 1 || score > 5) {
40
+ throw new Error(`Score is not a digit in the range 1-5: ${text}`);
41
+ }
42
+ const normalizedScore = (score - 1) / 4;
43
+ return Promise.resolve({
44
+ reasoning,
45
+ score: normalizedScore,
46
+ });
47
+ }
48
+ }
49
+ /**
50
+ * A chain for evaluating ReAct style agents.
51
+ *
52
+ * This chain is used to evaluate ReAct style agents by reasoning about
53
+ * the sequence of actions taken and their outcomes.
54
+ */
55
+ export class TrajectoryEvalChain extends AgentTrajectoryEvaluator {
56
+ constructor() {
57
+ super(...arguments);
58
+ Object.defineProperty(this, "criterionName", {
59
+ enumerable: true,
60
+ configurable: true,
61
+ writable: true,
62
+ value: void 0
63
+ });
64
+ Object.defineProperty(this, "evaluationName", {
65
+ enumerable: true,
66
+ configurable: true,
67
+ writable: true,
68
+ value: this.criterionName
69
+ });
70
+ Object.defineProperty(this, "requiresInput", {
71
+ enumerable: true,
72
+ configurable: true,
73
+ writable: true,
74
+ value: true
75
+ });
76
+ Object.defineProperty(this, "requiresReference", {
77
+ enumerable: true,
78
+ configurable: true,
79
+ writable: true,
80
+ value: false
81
+ });
82
+ Object.defineProperty(this, "outputParser", {
83
+ enumerable: true,
84
+ configurable: true,
85
+ writable: true,
86
+ value: new TrajectoryOutputParser()
87
+ });
88
+ }
89
+ static lc_name() {
90
+ return "TrajectoryEvalChain";
91
+ }
92
+ static resolveTrajectoryPrompt(prompt, agentTools) {
93
+ let _prompt;
94
+ if (prompt) {
95
+ _prompt = prompt;
96
+ }
97
+ else if (agentTools) {
98
+ _prompt = EVAL_CHAT_PROMPT;
99
+ }
100
+ else {
101
+ _prompt = TOOL_FREE_EVAL_CHAT_PROMPT;
102
+ }
103
+ return _prompt;
104
+ }
105
+ /**
106
+ * Get the description of the agent tools.
107
+ *
108
+ * @returns The description of the agent tools.
109
+ */
110
+ static toolsDescription(agentTools) {
111
+ return agentTools
112
+ .map((tool, i) => `Tool ${i + 1}: ${tool.name}\n Description: ${tool.description}`)
113
+ .join("\n\n");
114
+ }
115
+ /**
116
+ * Create a new TrajectoryEvalChain.
117
+ * @param llm
118
+ * @param agentTools - The tools used by the agent.
119
+ * @param chainOptions - The options for the chain.
120
+ */
121
+ static async fromLLM(llm, agentTools, chainOptions) {
122
+ let prompt = this.resolveTrajectoryPrompt(chainOptions?.prompt, agentTools);
123
+ if (agentTools) {
124
+ const toolDescriptions = this.toolsDescription(agentTools);
125
+ prompt = await prompt.partial({ toolDescriptions });
126
+ }
127
+ const options = chainOptions;
128
+ if (options) {
129
+ // remove prompt from chainOptions
130
+ delete options.prompt;
131
+ }
132
+ return new this({
133
+ llm,
134
+ prompt,
135
+ ...options,
136
+ });
137
+ }
138
+ _prepareOutput(result) {
139
+ const parsed = result[this.outputKey];
140
+ if (RUN_KEY in result && result[RUN_KEY]) {
141
+ parsed[RUN_KEY] = result[RUN_KEY];
142
+ }
143
+ return parsed;
144
+ }
145
+ /**
146
+ * Get the agent trajectory as a formatted string.
147
+ *
148
+ * @param steps - The agent trajectory.
149
+ * @returns The formatted agent trajectory.
150
+ */
151
+ getAgentTrajectory(steps) {
152
+ return steps
153
+ .map((step, i) => {
154
+ const { action, observation } = step;
155
+ return (`Step ${i + 1}:\n` +
156
+ `Tool used: ${action.tool}\n` +
157
+ `Tool input: ${action.toolInput}\n` +
158
+ `Tool output: ${observation}`);
159
+ })
160
+ .join("\n\n");
161
+ }
162
+ formatReference(reference) {
163
+ if (!reference) {
164
+ return "";
165
+ }
166
+ return `
167
+ The following is the expected answer. Use this to measure correctness:
168
+ [GROUND_TRUTH]
169
+ ${reference}
170
+ [END_GROUND_TRUTH]
171
+ `;
172
+ }
173
+ async _evaluateAgentTrajectory(args, callOptions, config) {
174
+ const { input, prediction, reference, agentTrajectory } = args;
175
+ const inputs = {
176
+ question: input,
177
+ agentTrajectory: this.getAgentTrajectory(agentTrajectory),
178
+ answer: prediction,
179
+ reference: this.formatReference(reference),
180
+ };
181
+ const result = await this.call({ ...inputs, ...callOptions }, config);
182
+ return this._prepareOutput(result);
183
+ }
184
+ }
@@ -0,0 +1,274 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.AgentTrajectoryEvaluator = exports.LLMPairwiseStringEvaluator = exports.PairwiseStringEvaluator = exports.StringEvaluator = exports.LLMStringEvaluator = exports.EvalChain = exports.LLMEvalChain = exports.eqSet = void 0;
4
+ const index_js_1 = require("../chains/index.cjs");
5
+ /**
6
+ * Compare two sets for equality
7
+ *
8
+ * @param xs
9
+ * @param ys
10
+ */
11
+ const eqSet = (xs, ys) => xs.size === ys.size && [...xs].every((x) => ys.has(x));
12
+ exports.eqSet = eqSet;
13
+ /**
14
+ * Base llm chain class for evaluators.
15
+ */
16
+ class LLMEvalChain extends index_js_1.LLMChain {
17
+ constructor() {
18
+ super(...arguments);
19
+ Object.defineProperty(this, "requiresInput", {
20
+ enumerable: true,
21
+ configurable: true,
22
+ writable: true,
23
+ value: false
24
+ });
25
+ Object.defineProperty(this, "requiresReference", {
26
+ enumerable: true,
27
+ configurable: true,
28
+ writable: true,
29
+ value: false
30
+ });
31
+ Object.defineProperty(this, "skipInputWarning", {
32
+ enumerable: true,
33
+ configurable: true,
34
+ writable: true,
35
+ value: `Ignoring input in ${this.constructor.name}, as it is not expected.`
36
+ });
37
+ Object.defineProperty(this, "skipReferenceWarning", {
38
+ enumerable: true,
39
+ configurable: true,
40
+ writable: true,
41
+ value: `Ignoring reference in ${this.constructor.name}, as it is not expected.`
42
+ });
43
+ }
44
+ /**
45
+ * Check if the evaluation arguments are valid.
46
+ * @param reference The reference label.
47
+ * @param input The input string.
48
+ * @throws {Error} If the evaluator requires an input string but none is provided, or if the evaluator requires a reference label but none is provided.
49
+ */
50
+ checkEvaluationArgs(reference, input) {
51
+ if (this.requiresInput && input == null) {
52
+ throw new Error(`${this.constructor.name} requires an input string.`);
53
+ }
54
+ else if (input != null && !this.requiresInput) {
55
+ console.warn(this.skipInputWarning);
56
+ }
57
+ if (this.requiresReference && reference == null) {
58
+ throw new Error(`${this.constructor.name} requires a reference string.`);
59
+ }
60
+ else if (reference != null && !this.requiresReference) {
61
+ console.warn(this.skipReferenceWarning);
62
+ }
63
+ }
64
+ }
65
+ exports.LLMEvalChain = LLMEvalChain;
66
+ /**
67
+ * Base chain class for evaluators.
68
+ */
69
+ class EvalChain extends index_js_1.BaseChain {
70
+ constructor() {
71
+ super(...arguments);
72
+ Object.defineProperty(this, "requiresInput", {
73
+ enumerable: true,
74
+ configurable: true,
75
+ writable: true,
76
+ value: false
77
+ });
78
+ Object.defineProperty(this, "requiresReference", {
79
+ enumerable: true,
80
+ configurable: true,
81
+ writable: true,
82
+ value: false
83
+ });
84
+ Object.defineProperty(this, "skipInputWarning", {
85
+ enumerable: true,
86
+ configurable: true,
87
+ writable: true,
88
+ value: `Ignoring input in ${this.constructor.name}, as it is not expected.`
89
+ });
90
+ Object.defineProperty(this, "skipReferenceWarning", {
91
+ enumerable: true,
92
+ configurable: true,
93
+ writable: true,
94
+ value: `Ignoring reference in ${this.constructor.name}, as it is not expected.`
95
+ });
96
+ }
97
+ /**
98
+ * Check if the evaluation arguments are valid.
99
+ * @param reference The reference label.
100
+ * @param input The input string.
101
+ * @throws {Error} If the evaluator requires an input string but none is provided, or if the evaluator requires a reference label but none is provided.
102
+ */
103
+ checkEvaluationArgs(reference, input) {
104
+ if (this.requiresInput && input == null) {
105
+ throw new Error(`${this.constructor.name} requires an input string.`);
106
+ }
107
+ else if (input != null && !this.requiresInput) {
108
+ console.warn(this.skipInputWarning);
109
+ }
110
+ if (this.requiresReference && reference == null) {
111
+ throw new Error(`${this.constructor.name} requires a reference string.`);
112
+ }
113
+ else if (reference != null && !this.requiresReference) {
114
+ console.warn(this.skipReferenceWarning);
115
+ }
116
+ }
117
+ }
118
+ exports.EvalChain = EvalChain;
119
+ /**
120
+ * Grade, tag, or otherwise evaluate predictions relative to their inputs
121
+ * and/or reference labels
122
+ */
123
+ class LLMStringEvaluator extends LLMEvalChain {
124
+ constructor() {
125
+ super(...arguments);
126
+ /**
127
+ * The name of the evaluation.
128
+ */
129
+ Object.defineProperty(this, "evaluationName", {
130
+ enumerable: true,
131
+ configurable: true,
132
+ writable: true,
133
+ value: this.constructor.name
134
+ });
135
+ }
136
+ /**
137
+ * Evaluate Chain or LLM output, based on optional input and label.
138
+ * @returns The evaluation results containing the score or value. It is recommended that the dictionary contain the following keys:
139
+ * - score: the score of the evaluation, if applicable.
140
+ * - value: the string value of the evaluation, if applicable.
141
+ * - reasoning: the reasoning for the evaluation, if applicable.
142
+ * @param args
143
+ * @param callOptions
144
+ * @param config
145
+ */
146
+ evaluateStrings(args, callOptions, config) {
147
+ this.checkEvaluationArgs(args.reference, args.input);
148
+ return this._evaluateStrings(args, callOptions, config);
149
+ }
150
+ }
151
+ exports.LLMStringEvaluator = LLMStringEvaluator;
152
+ /**
153
+ * Grade, tag, or otherwise evaluate predictions relative to their inputs
154
+ * and/or reference labels
155
+ */
156
+ class StringEvaluator extends EvalChain {
157
+ constructor() {
158
+ super(...arguments);
159
+ /**
160
+ * The name of the evaluation.
161
+ */
162
+ Object.defineProperty(this, "evaluationName", {
163
+ enumerable: true,
164
+ configurable: true,
165
+ writable: true,
166
+ value: this.constructor.name
167
+ });
168
+ }
169
+ /**
170
+ * Evaluate Chain or LLM output, based on optional input and label.
171
+ * @returns The evaluation results containing the score or value. It is recommended that the dictionary contain the following keys:
172
+ * - score: the score of the evaluation, if applicable.
173
+ * - value: the string value of the evaluation, if applicable.
174
+ * - reasoning: the reasoning for the evaluation, if applicable.
175
+ * @param args
176
+ * @param config
177
+ */
178
+ evaluateStrings(args, config) {
179
+ this.checkEvaluationArgs(args.reference, args.input);
180
+ return this._evaluateStrings(args, config);
181
+ }
182
+ }
183
+ exports.StringEvaluator = StringEvaluator;
184
+ /**
185
+ * Compare the output of two models (or two outputs of the same model).
186
+ */
187
+ class PairwiseStringEvaluator extends EvalChain {
188
+ constructor() {
189
+ super(...arguments);
190
+ /**
191
+ * The name of the evaluation.
192
+ */
193
+ Object.defineProperty(this, "evaluationName", {
194
+ enumerable: true,
195
+ configurable: true,
196
+ writable: true,
197
+ value: this.constructor.name
198
+ });
199
+ }
200
+ /**
201
+ * Evaluate the output string pairs.
202
+ * @param args
203
+ * @param config
204
+ * @return A dictionary containing the preference, scores, and/or other information.
205
+ */
206
+ evaluateStringPairs(args, config) {
207
+ return this._evaluateStringPairs(args, config);
208
+ }
209
+ }
210
+ exports.PairwiseStringEvaluator = PairwiseStringEvaluator;
211
+ /**
212
+ * Compare the output of two models (or two outputs of the same model).
213
+ */
214
+ class LLMPairwiseStringEvaluator extends LLMEvalChain {
215
+ constructor() {
216
+ super(...arguments);
217
+ /**
218
+ * The name of the evaluation.
219
+ */
220
+ Object.defineProperty(this, "evaluationName", {
221
+ enumerable: true,
222
+ configurable: true,
223
+ writable: true,
224
+ value: this.constructor.name
225
+ });
226
+ }
227
+ /**
228
+ * Evaluate the output string pairs.
229
+ * @param args
230
+ * @param callOptions
231
+ * @param config
232
+ * @return A dictionary containing the preference, scores, and/or other information.
233
+ */
234
+ evaluateStringPairs(args, callOptions, config) {
235
+ this.checkEvaluationArgs(args.reference, args.input);
236
+ return this._evaluateStringPairs(args, callOptions, config);
237
+ }
238
+ }
239
+ exports.LLMPairwiseStringEvaluator = LLMPairwiseStringEvaluator;
240
+ /**
241
+ * Interface for evaluating agent trajectories.
242
+ */
243
+ class AgentTrajectoryEvaluator extends LLMEvalChain {
244
+ constructor() {
245
+ super(...arguments);
246
+ Object.defineProperty(this, "requiresInput", {
247
+ enumerable: true,
248
+ configurable: true,
249
+ writable: true,
250
+ value: true
251
+ });
252
+ /**
253
+ * The name of the evaluation.
254
+ */
255
+ Object.defineProperty(this, "evaluationName", {
256
+ enumerable: true,
257
+ configurable: true,
258
+ writable: true,
259
+ value: this.constructor.name
260
+ });
261
+ }
262
+ /**
263
+ * Evaluate a trajectory.
264
+ * @return The evaluation result.
265
+ * @param args
266
+ * @param callOptions
267
+ * @param config
268
+ */
269
+ evaluateAgentTrajectory(args, callOptions, config) {
270
+ this.checkEvaluationArgs(args.reference, args.input);
271
+ return this._evaluateAgentTrajectory(args, callOptions, config);
272
+ }
273
+ }
274
+ exports.AgentTrajectoryEvaluator = AgentTrajectoryEvaluator;