langchain 0.1.5 → 0.1.7

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.
@@ -0,0 +1,356 @@
1
+ import { mapStoredMessagesToChatMessages } from "@langchain/core/messages";
2
+ import { Runnable, RunnableLambda, } from "@langchain/core/runnables";
3
+ import { RunCollectorCallbackHandler } from "@langchain/core/tracers/run_collector";
4
+ import { LangChainTracer } from "@langchain/core/tracers/tracer_langchain";
5
+ import { Client } from "langsmith";
6
+ import { loadEvaluator } from "../evaluation/loader.js";
7
+ import { randomName } from "./name_generation.js";
8
+ import { ProgressBar } from "./progress.js";
9
+ /**
10
+ * Wraps an evaluator function + implements the RunEvaluator interface.
11
+ */
12
+ class DynamicRunEvaluator {
13
+ constructor(evaluator) {
14
+ Object.defineProperty(this, "evaluator", {
15
+ enumerable: true,
16
+ configurable: true,
17
+ writable: true,
18
+ value: void 0
19
+ });
20
+ this.evaluator = new RunnableLambda({ func: evaluator });
21
+ }
22
+ /**
23
+ * Evaluates a run with an optional example and returns the evaluation result.
24
+ * @param run The run to evaluate.
25
+ * @param example The optional example to use for evaluation.
26
+ * @returns A promise that resolves to the evaluation result.
27
+ */
28
+ async evaluateRun(run, example) {
29
+ return await this.evaluator.invoke({
30
+ run,
31
+ example,
32
+ input: run.inputs,
33
+ prediction: run.outputs,
34
+ reference: example?.outputs,
35
+ });
36
+ }
37
+ }
38
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
39
+ function isLLMStringEvaluator(evaluator) {
40
+ return evaluator && typeof evaluator.evaluateStrings === "function";
41
+ }
42
+ /**
43
+ * Wraps an off-the-shelf evaluator (loaded using loadEvaluator; of EvaluatorType[T])
44
+ * and composes with a prepareData function so the user can prepare the trace and
45
+ * dataset data for the evaluator.
46
+ */
47
+ class PreparedRunEvaluator {
48
+ constructor(evaluator, evaluationName, formatEvaluatorInputs) {
49
+ Object.defineProperty(this, "evaluator", {
50
+ enumerable: true,
51
+ configurable: true,
52
+ writable: true,
53
+ value: void 0
54
+ });
55
+ Object.defineProperty(this, "formatEvaluatorInputs", {
56
+ enumerable: true,
57
+ configurable: true,
58
+ writable: true,
59
+ value: void 0
60
+ });
61
+ Object.defineProperty(this, "isStringEvaluator", {
62
+ enumerable: true,
63
+ configurable: true,
64
+ writable: true,
65
+ value: void 0
66
+ });
67
+ Object.defineProperty(this, "evaluationName", {
68
+ enumerable: true,
69
+ configurable: true,
70
+ writable: true,
71
+ value: void 0
72
+ });
73
+ this.evaluator = evaluator;
74
+ this.isStringEvaluator = typeof evaluator?.evaluateStrings === "function";
75
+ this.evaluationName = evaluationName;
76
+ this.formatEvaluatorInputs = formatEvaluatorInputs;
77
+ }
78
+ static async fromEvalConfig(config) {
79
+ const evaluatorType = typeof config === "string" ? config : config.evaluatorType;
80
+ const evalConfig = typeof config === "string" ? {} : config;
81
+ const evaluator = await loadEvaluator(evaluatorType, evalConfig);
82
+ const feedbackKey = evalConfig?.feedbackKey ?? evaluator?.evaluationName;
83
+ if (!feedbackKey) {
84
+ throw new Error(`Evaluator of type ${evaluatorType} must have an evaluationName` +
85
+ ` or feedbackKey. Please manually provide a feedbackKey in the EvalConfig.`);
86
+ }
87
+ if (!isLLMStringEvaluator(evaluator)) {
88
+ throw new Error(`Evaluator of type ${evaluatorType} not yet supported. ` +
89
+ "Please use a string evaluator, or implement your " +
90
+ "evaluation logic as a customEvaluator.");
91
+ }
92
+ return new PreparedRunEvaluator(evaluator, feedbackKey, evalConfig?.formatEvaluatorInputs);
93
+ }
94
+ /**
95
+ * Evaluates a run with an optional example and returns the evaluation result.
96
+ * @param run The run to evaluate.
97
+ * @param example The optional example to use for evaluation.
98
+ * @returns A promise that resolves to the evaluation result.
99
+ */
100
+ async evaluateRun(run, example) {
101
+ const { prediction, input, reference } = this.formatEvaluatorInputs({
102
+ rawInput: run.inputs,
103
+ rawPrediction: run.outputs,
104
+ rawReferenceOutput: example?.outputs,
105
+ run,
106
+ });
107
+ if (this.isStringEvaluator) {
108
+ const evalResult = await this.evaluator.evaluateStrings({
109
+ prediction: prediction,
110
+ reference: reference,
111
+ input: input,
112
+ });
113
+ return {
114
+ key: this.evaluationName,
115
+ comment: evalResult?.reasoning,
116
+ ...evalResult,
117
+ };
118
+ }
119
+ throw new Error("Evaluator not yet supported. " +
120
+ "Please use a string evaluator, or implement your " +
121
+ "evaluation logic as a customEvaluator.");
122
+ }
123
+ }
124
+ class LoadedEvalConfig {
125
+ constructor(evaluators) {
126
+ Object.defineProperty(this, "evaluators", {
127
+ enumerable: true,
128
+ configurable: true,
129
+ writable: true,
130
+ value: evaluators
131
+ });
132
+ }
133
+ static async fromRunEvalConfig(config) {
134
+ // Custom evaluators are applied "as-is"
135
+ const customEvaluators = config?.customEvaluators?.map((evaluator) => {
136
+ if (typeof evaluator === "function") {
137
+ return new DynamicRunEvaluator(evaluator);
138
+ }
139
+ else {
140
+ return evaluator;
141
+ }
142
+ });
143
+ const offTheShelfEvaluators = await Promise.all(config?.evaluators?.map(async (evaluator) => await PreparedRunEvaluator.fromEvalConfig(evaluator)) ?? []);
144
+ return new LoadedEvalConfig((customEvaluators ?? []).concat(offTheShelfEvaluators ?? []));
145
+ }
146
+ }
147
+ /**
148
+ * Internals expect a constructor () -> Runnable. This function wraps/coerces
149
+ * the provided LangChain object, custom function, or factory function into
150
+ * a constructor of a runnable.
151
+ * @param modelOrFactory The model or factory to create a wrapped model from.
152
+ * @returns A function that returns the wrapped model.
153
+ * @throws Error if the modelOrFactory is invalid.
154
+ */
155
+ const createWrappedModel = async (modelOrFactory) => {
156
+ if (Runnable.isRunnable(modelOrFactory)) {
157
+ return () => modelOrFactory;
158
+ }
159
+ if (typeof modelOrFactory === "function") {
160
+ try {
161
+ // If it works with no arguments, assume it's a factory
162
+ let res = modelOrFactory();
163
+ if (res &&
164
+ typeof res.then === "function") {
165
+ res = await res;
166
+ }
167
+ return modelOrFactory;
168
+ }
169
+ catch (err) {
170
+ // Otherwise, it's a custom UDF, and we'll wrap
171
+ // in a lambda
172
+ const wrappedModel = new RunnableLambda({ func: modelOrFactory });
173
+ return () => wrappedModel;
174
+ }
175
+ }
176
+ throw new Error("Invalid modelOrFactory");
177
+ };
178
+ const loadExamples = async ({ datasetName, client, projectName, }) => {
179
+ const exampleIterator = client.listExamples({ datasetName });
180
+ const configs = [];
181
+ const runCollectors = [];
182
+ const examples = [];
183
+ for await (const example of exampleIterator) {
184
+ const runCollector = new RunCollectorCallbackHandler({
185
+ exampleId: example.id,
186
+ });
187
+ configs.push({
188
+ callbacks: [
189
+ new LangChainTracer({ exampleId: example.id, projectName }),
190
+ runCollector,
191
+ ],
192
+ });
193
+ examples.push(example);
194
+ runCollectors.push(runCollector);
195
+ }
196
+ return {
197
+ configs,
198
+ examples,
199
+ runCollectors,
200
+ };
201
+ };
202
+ const applyEvaluators = async ({ evaluation, runs, examples, client, }) => {
203
+ // TODO: Parallelize and/or put in callbacks to speed up evals.
204
+ const { evaluators } = evaluation;
205
+ const progress = new ProgressBar({
206
+ total: examples.length,
207
+ format: "Running Evaluators: {bar} {percentage}% | {value}/{total}\n",
208
+ });
209
+ const results = {};
210
+ for (let i = 0; i < runs.length; i += 1) {
211
+ const run = runs[i];
212
+ const example = examples[i];
213
+ const evaluatorResults = await Promise.all(evaluators.map((evaluator) => client.evaluateRun(run, evaluator, {
214
+ referenceExample: example,
215
+ loadChildRuns: false,
216
+ })));
217
+ progress.increment();
218
+ results[example.id] = {
219
+ execution_time: run?.end_time && run.start_time
220
+ ? run.end_time - run.start_time
221
+ : undefined,
222
+ feedback: evaluatorResults,
223
+ run_id: run.id,
224
+ };
225
+ }
226
+ return results;
227
+ };
228
+ const getExamplesInputs = (examples, chainOrFactory, dataType) => {
229
+ if (dataType === "chat") {
230
+ // For some batty reason, we store the chat dataset differently.
231
+ // { type: "system", data: { content: inputs.input } },
232
+ // But we need to create AIMesage, SystemMessage, etc.
233
+ return examples.map(({ inputs }) => mapStoredMessagesToChatMessages(inputs.input));
234
+ }
235
+ // If it's a language model and ALL example inputs have a single value,
236
+ // then we can be friendly and flatten the inputs to a list of strings.
237
+ const isLanguageModel = typeof chainOrFactory === "object" &&
238
+ typeof chainOrFactory._llmType === "function";
239
+ if (isLanguageModel &&
240
+ examples.every(({ inputs }) => Object.keys(inputs).length === 1)) {
241
+ return examples.map(({ inputs }) => Object.values(inputs)[0]);
242
+ }
243
+ return examples.map(({ inputs }) => inputs);
244
+ };
245
+ /**
246
+ * Evaluates a given model or chain against a specified LangSmith dataset.
247
+ *
248
+ * This function fetches example records from the specified dataset,
249
+ * runs the model or chain against each example, and returns the evaluation
250
+ * results.
251
+ *
252
+ * @param chainOrFactory - A model or factory/constructor function to be evaluated. It can be a
253
+ * Runnable instance, a factory function that returns a Runnable, or a user-defined
254
+ * function or factory.
255
+ *
256
+ * @param datasetName - The name of the dataset against which the evaluation will be
257
+ * performed. This dataset should already be defined and contain the relevant data
258
+ * for evaluation.
259
+ *
260
+ * @param options - (Optional) Additional parameters for the evaluation process:
261
+ * - `evaluationConfig` (RunEvalConfig): Configuration for the evaluation, including
262
+ * standard and custom evaluators.
263
+ * - `projectName` (string): Name of the project for logging and tracking.
264
+ * - `projectMetadata` (Record<string, unknown>): Additional metadata for the project.
265
+ * - `client` (Client): Client instance for LangChain service interaction.
266
+ * - `maxConcurrency` (number): Maximum concurrency level for dataset processing.
267
+ *
268
+ * @returns A promise that resolves to an `EvalResults` object. This object includes
269
+ * detailed results of the evaluation, such as execution time, run IDs, and feedback
270
+ * for each entry in the dataset.
271
+ *
272
+ * @example
273
+ * ```typescript
274
+ * // Example usage for evaluating a model on a dataset
275
+ * async function evaluateModel() {
276
+ * const chain = /* ...create your model or chain...*\//
277
+ * const datasetName = 'example-dataset';
278
+ * const client = new Client(/* ...config... *\//);
279
+ *
280
+ * const evaluationConfig = {
281
+ * evaluators: [/* ...evaluators... *\//],
282
+ * customEvaluators: [/* ...custom evaluators... *\//],
283
+ * };
284
+ *
285
+ * const results = await runOnDataset(chain, datasetName, {
286
+ * evaluationConfig,
287
+ * client,
288
+ * });
289
+ *
290
+ * console.log('Evaluation Results:', results);
291
+ * }
292
+ *
293
+ * evaluateModel();
294
+ * ```
295
+ * In this example, `runOnDataset` is used to evaluate a language model (or a chain of models) against
296
+ * a dataset named 'example-dataset'. The evaluation process is configured using `RunEvalConfig`, which can
297
+ * include both standard and custom evaluators. The `Client` instance is used to interact with LangChain services.
298
+ * The function returns the evaluation results, which can be logged or further processed as needed.
299
+ */
300
+ export const runOnDataset = async (chainOrFactory, datasetName, { evaluationConfig, projectName, projectMetadata, client, maxConcurrency, }) => {
301
+ const wrappedModel = await createWrappedModel(chainOrFactory);
302
+ const testClient = client ?? new Client();
303
+ const testProjectName = projectName ?? randomName();
304
+ const dataset = await testClient.readDataset({ datasetName });
305
+ const datasetId = dataset.id;
306
+ const testConcurrency = maxConcurrency ?? 5;
307
+ const { configs, examples, runCollectors } = await loadExamples({
308
+ datasetName,
309
+ client: testClient,
310
+ projectName: testProjectName,
311
+ maxConcurrency: testConcurrency,
312
+ });
313
+ await testClient.createProject({
314
+ projectName: testProjectName,
315
+ referenceDatasetId: datasetId,
316
+ projectExtra: { metadata: { ...projectMetadata } },
317
+ });
318
+ const wrappedRunnable = new RunnableLambda({
319
+ func: wrappedModel,
320
+ }).withConfig({ runName: "evaluationRun" });
321
+ const runInputs = getExamplesInputs(examples, chainOrFactory, dataset.data_type);
322
+ const progress = new ProgressBar({
323
+ total: runInputs.length,
324
+ format: "Predicting: {bar} {percentage}% | {value}/{total}",
325
+ });
326
+ // TODO: Collect the runs as well.
327
+ await wrappedRunnable
328
+ .withListeners({
329
+ onEnd: () => progress.increment(),
330
+ })
331
+ // TODO: Insert evaluation inline for immediate feedback.
332
+ .batch(runInputs, configs, {
333
+ maxConcurrency,
334
+ returnExceptions: true,
335
+ });
336
+ progress.complete();
337
+ const runs = [];
338
+ for (let i = 0; i < examples.length; i += 1) {
339
+ runs.push(runCollectors[i].tracedRuns[0]);
340
+ }
341
+ let evalResults = {};
342
+ if (evaluationConfig) {
343
+ const loadedEvalConfig = await LoadedEvalConfig.fromRunEvalConfig(evaluationConfig);
344
+ evalResults = await applyEvaluators({
345
+ evaluation: loadedEvalConfig,
346
+ runs,
347
+ examples,
348
+ client: testClient,
349
+ });
350
+ }
351
+ const results = {
352
+ projectName: testProjectName,
353
+ results: evalResults ?? {},
354
+ };
355
+ return results;
356
+ };
package/indexes.cjs ADDED
@@ -0,0 +1 @@
1
+ module.exports = require('./dist/indexes/index.cjs');
package/indexes.d.ts ADDED
@@ -0,0 +1 @@
1
+ export * from './dist/indexes/index.js'
package/indexes.js ADDED
@@ -0,0 +1 @@
1
+ export * from './dist/indexes/index.js'
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "langchain",
3
- "version": "0.1.5",
3
+ "version": "0.1.7",
4
4
  "description": "Typescript bindings for langchain",
5
5
  "type": "module",
6
6
  "engines": {
@@ -865,12 +865,18 @@
865
865
  "evaluation.cjs",
866
866
  "evaluation.js",
867
867
  "evaluation.d.ts",
868
+ "smith.cjs",
869
+ "smith.js",
870
+ "smith.d.ts",
868
871
  "runnables.cjs",
869
872
  "runnables.js",
870
873
  "runnables.d.ts",
871
874
  "runnables/remote.cjs",
872
875
  "runnables/remote.js",
873
876
  "runnables/remote.d.ts",
877
+ "indexes.cjs",
878
+ "indexes.js",
879
+ "indexes.d.ts",
874
880
  "index.cjs",
875
881
  "index.js",
876
882
  "index.d.ts"
@@ -1001,7 +1007,7 @@
1001
1007
  "@google-ai/generativelanguage": "^0.2.1",
1002
1008
  "@google-cloud/storage": "^6.10.1",
1003
1009
  "@notionhq/client": "^2.2.10",
1004
- "@pinecone-database/pinecone": "^1.1.0",
1010
+ "@pinecone-database/pinecone": "*",
1005
1011
  "@supabase/supabase-js": "^2.10.0",
1006
1012
  "@vercel/kv": "^0.2.3",
1007
1013
  "@xata.io/client": "^0.28.0",
@@ -1202,7 +1208,7 @@
1202
1208
  },
1203
1209
  "dependencies": {
1204
1210
  "@anthropic-ai/sdk": "^0.9.1",
1205
- "@langchain/community": "~0.0.17",
1211
+ "@langchain/community": "~0.0.20",
1206
1212
  "@langchain/core": "~0.1.16",
1207
1213
  "@langchain/openai": "~0.0.12",
1208
1214
  "binary-extensions": "^2.2.0",
@@ -1211,7 +1217,7 @@
1211
1217
  "js-yaml": "^4.1.0",
1212
1218
  "jsonpointer": "^5.0.1",
1213
1219
  "langchainhub": "~0.0.6",
1214
- "langsmith": "~0.0.48",
1220
+ "langsmith": "~0.0.59",
1215
1221
  "ml-distance": "^4.0.0",
1216
1222
  "openapi-types": "^12.1.3",
1217
1223
  "p-retry": "4",
@@ -2663,6 +2669,11 @@
2663
2669
  "import": "./evaluation.js",
2664
2670
  "require": "./evaluation.cjs"
2665
2671
  },
2672
+ "./smith": {
2673
+ "types": "./smith.d.ts",
2674
+ "import": "./smith.js",
2675
+ "require": "./smith.cjs"
2676
+ },
2666
2677
  "./runnables": {
2667
2678
  "types": "./runnables.d.ts",
2668
2679
  "import": "./runnables.js",
@@ -2673,6 +2684,11 @@
2673
2684
  "import": "./runnables/remote.js",
2674
2685
  "require": "./runnables/remote.cjs"
2675
2686
  },
2687
+ "./indexes": {
2688
+ "types": "./indexes.d.ts",
2689
+ "import": "./indexes.js",
2690
+ "require": "./indexes.cjs"
2691
+ },
2676
2692
  "./package.json": "./package.json"
2677
2693
  }
2678
2694
  }
package/smith.cjs ADDED
@@ -0,0 +1 @@
1
+ module.exports = require('./dist/smith/index.cjs');
package/smith.d.ts ADDED
@@ -0,0 +1 @@
1
+ export * from './dist/smith/index.js'
package/smith.js ADDED
@@ -0,0 +1 @@
1
+ export * from './dist/smith/index.js'