langsmith 0.1.21 → 0.1.22

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.
@@ -1,2 +1,88 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.runEvaluator = exports.DynamicRunEvaluator = void 0;
4
+ const uuid_1 = require("uuid");
5
+ const traceable_js_1 = require("../traceable.cjs");
6
+ /**
7
+ * Wraps an evaluator function + implements the RunEvaluator interface.
8
+ */
9
+ class DynamicRunEvaluator {
10
+ constructor(evaluator) {
11
+ Object.defineProperty(this, "func", {
12
+ enumerable: true,
13
+ configurable: true,
14
+ writable: true,
15
+ value: void 0
16
+ });
17
+ const wrappedFunc = (input) => {
18
+ const runAndExample = input.langSmithRunAndExample;
19
+ return evaluator(...Object.values(runAndExample));
20
+ };
21
+ this.func = wrappedFunc;
22
+ }
23
+ coerceEvaluationResults(results, sourceRunId) {
24
+ if ("results" in results) {
25
+ throw new Error("EvaluationResults not supported yet.");
26
+ }
27
+ return this.coerceEvaluationResult(results, sourceRunId, true);
28
+ }
29
+ coerceEvaluationResult(result, sourceRunId, allowNoKey = false) {
30
+ if ("key" in result) {
31
+ if (!result.sourceRunId) {
32
+ result.sourceRunId = sourceRunId;
33
+ }
34
+ return result;
35
+ }
36
+ if (!("key" in result)) {
37
+ if (allowNoKey) {
38
+ result["key"] = this.func.name;
39
+ }
40
+ }
41
+ return {
42
+ sourceRunId,
43
+ ...result,
44
+ };
45
+ }
46
+ /**
47
+ * Evaluates a run with an optional example and returns the evaluation result.
48
+ * @param run The run to evaluate.
49
+ * @param example The optional example to use for evaluation.
50
+ * @returns A promise that extracts to the evaluation result.
51
+ */
52
+ async evaluateRun(run, example, options) {
53
+ const sourceRunId = (0, uuid_1.v4)();
54
+ const metadata = {
55
+ targetRunId: run.id,
56
+ };
57
+ if ("session_id" in run) {
58
+ metadata["experiment"] = run.session_id;
59
+ }
60
+ const wrappedTraceableFunc = (0, traceable_js_1.wrapFunctionAndEnsureTraceable)(this.func, options || {}, "evaluator");
61
+ // Pass data via `langSmithRunAndExample` key to avoid conflicts with other
62
+ // inputs. This key is extracted in the wrapped function, with `run` and
63
+ // `example` passed to evaluator function as arguments.
64
+ const langSmithRunAndExample = {
65
+ run,
66
+ example,
67
+ };
68
+ const result = (await wrappedTraceableFunc({ langSmithRunAndExample }, {
69
+ metadata,
70
+ }));
71
+ // Check the one required property of EvaluationResult since 'instanceof' is not possible
72
+ if ("key" in result) {
73
+ if (!result.sourceRunId) {
74
+ result.sourceRunId = sourceRunId;
75
+ }
76
+ return result;
77
+ }
78
+ if (typeof result !== "object") {
79
+ throw new Error("Evaluator function must return an object.");
80
+ }
81
+ return this.coerceEvaluationResults(result, sourceRunId);
82
+ }
83
+ }
84
+ exports.DynamicRunEvaluator = DynamicRunEvaluator;
85
+ function runEvaluator(func) {
86
+ return new DynamicRunEvaluator(func);
87
+ }
88
+ exports.runEvaluator = runEvaluator;
@@ -1,4 +1,5 @@
1
- import { Example, Run, ScoreType, ValueType } from "../schemas.js";
1
+ import { Example, FeedbackConfig, Run, ScoreType, ValueType } from "../schemas.js";
2
+ import { RunTreeConfig } from "../run_trees.js";
2
3
  /**
3
4
  * Represents a categorical class.
4
5
  */
@@ -12,31 +13,6 @@ export type Category = {
12
13
  */
13
14
  label: string;
14
15
  };
15
- /**
16
- * Configuration for feedback.
17
- */
18
- export type FeedbackConfig = {
19
- /**
20
- * The type of feedback.
21
- * - "continuous": Feedback with a continuous numeric.
22
- * - "categorical": Feedback with a categorical value (classes)
23
- * - "freeform": Feedback with a freeform text value (notes).
24
- */
25
- type: "continuous" | "categorical" | "freeform";
26
- /**
27
- * The minimum value for continuous feedback.
28
- */
29
- min?: number;
30
- /**
31
- * The maximum value for continuous feedback.
32
- */
33
- max?: number;
34
- /**
35
- * The categories for categorical feedback.
36
- * Each category can be a string or an object with additional properties.
37
- */
38
- categories?: (Category | Record<string, unknown>)[];
39
- };
40
16
  /**
41
17
  * Represents the result of an evaluation.
42
18
  */
@@ -83,6 +59,34 @@ export type EvaluationResult = {
83
59
  */
84
60
  feedbackConfig?: FeedbackConfig;
85
61
  };
62
+ /**
63
+ * Batch evaluation results, if your evaluator wishes
64
+ * to return multiple scores.
65
+ */
66
+ export type EvaluationResults = {
67
+ /**
68
+ * The evaluation results.
69
+ */
70
+ results: Array<EvaluationResult>;
71
+ };
86
72
  export interface RunEvaluator {
87
- evaluateRun(run: Run, example?: Example): Promise<EvaluationResult>;
73
+ evaluateRun(run: Run, example?: Example, options?: Partial<RunTreeConfig>): Promise<EvaluationResult>;
74
+ }
75
+ export type RunEvaluatorLike = ((run: Run, example?: Example) => Promise<EvaluationResult | EvaluationResults>) | ((run: Run, example?: Example) => EvaluationResult | EvaluationResults);
76
+ /**
77
+ * Wraps an evaluator function + implements the RunEvaluator interface.
78
+ */
79
+ export declare class DynamicRunEvaluator<Func extends (...args: any[]) => any> implements RunEvaluator {
80
+ func: Func;
81
+ constructor(evaluator: Func);
82
+ private coerceEvaluationResults;
83
+ private coerceEvaluationResult;
84
+ /**
85
+ * Evaluates a run with an optional example and returns the evaluation result.
86
+ * @param run The run to evaluate.
87
+ * @param example The optional example to use for evaluation.
88
+ * @returns A promise that extracts to the evaluation result.
89
+ */
90
+ evaluateRun(run: Run, example?: Example, options?: Partial<RunTreeConfig>): Promise<EvaluationResult>;
88
91
  }
92
+ export declare function runEvaluator(func: RunEvaluatorLike): RunEvaluator;
@@ -1 +1,83 @@
1
- export {};
1
+ import { v4 as uuidv4 } from "uuid";
2
+ import { wrapFunctionAndEnsureTraceable } from "../traceable.js";
3
+ /**
4
+ * Wraps an evaluator function + implements the RunEvaluator interface.
5
+ */
6
+ export class DynamicRunEvaluator {
7
+ constructor(evaluator) {
8
+ Object.defineProperty(this, "func", {
9
+ enumerable: true,
10
+ configurable: true,
11
+ writable: true,
12
+ value: void 0
13
+ });
14
+ const wrappedFunc = (input) => {
15
+ const runAndExample = input.langSmithRunAndExample;
16
+ return evaluator(...Object.values(runAndExample));
17
+ };
18
+ this.func = wrappedFunc;
19
+ }
20
+ coerceEvaluationResults(results, sourceRunId) {
21
+ if ("results" in results) {
22
+ throw new Error("EvaluationResults not supported yet.");
23
+ }
24
+ return this.coerceEvaluationResult(results, sourceRunId, true);
25
+ }
26
+ coerceEvaluationResult(result, sourceRunId, allowNoKey = false) {
27
+ if ("key" in result) {
28
+ if (!result.sourceRunId) {
29
+ result.sourceRunId = sourceRunId;
30
+ }
31
+ return result;
32
+ }
33
+ if (!("key" in result)) {
34
+ if (allowNoKey) {
35
+ result["key"] = this.func.name;
36
+ }
37
+ }
38
+ return {
39
+ sourceRunId,
40
+ ...result,
41
+ };
42
+ }
43
+ /**
44
+ * Evaluates a run with an optional example and returns the evaluation result.
45
+ * @param run The run to evaluate.
46
+ * @param example The optional example to use for evaluation.
47
+ * @returns A promise that extracts to the evaluation result.
48
+ */
49
+ async evaluateRun(run, example, options) {
50
+ const sourceRunId = uuidv4();
51
+ const metadata = {
52
+ targetRunId: run.id,
53
+ };
54
+ if ("session_id" in run) {
55
+ metadata["experiment"] = run.session_id;
56
+ }
57
+ const wrappedTraceableFunc = wrapFunctionAndEnsureTraceable(this.func, options || {}, "evaluator");
58
+ // Pass data via `langSmithRunAndExample` key to avoid conflicts with other
59
+ // inputs. This key is extracted in the wrapped function, with `run` and
60
+ // `example` passed to evaluator function as arguments.
61
+ const langSmithRunAndExample = {
62
+ run,
63
+ example,
64
+ };
65
+ const result = (await wrappedTraceableFunc({ langSmithRunAndExample }, {
66
+ metadata,
67
+ }));
68
+ // Check the one required property of EvaluationResult since 'instanceof' is not possible
69
+ if ("key" in result) {
70
+ if (!result.sourceRunId) {
71
+ result.sourceRunId = sourceRunId;
72
+ }
73
+ return result;
74
+ }
75
+ if (typeof result !== "object") {
76
+ throw new Error("Evaluator function must return an object.");
77
+ }
78
+ return this.coerceEvaluationResults(result, sourceRunId);
79
+ }
80
+ }
81
+ export function runEvaluator(func) {
82
+ return new DynamicRunEvaluator(func);
83
+ }
@@ -1,5 +1,7 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.StringEvaluator = void 0;
3
+ exports.evaluate = exports.StringEvaluator = void 0;
4
4
  var string_evaluator_js_1 = require("./string_evaluator.cjs");
5
5
  Object.defineProperty(exports, "StringEvaluator", { enumerable: true, get: function () { return string_evaluator_js_1.StringEvaluator; } });
6
+ var _runner_js_1 = require("./_runner.cjs");
7
+ Object.defineProperty(exports, "evaluate", { enumerable: true, get: function () { return _runner_js_1.evaluate; } });
@@ -1,2 +1,3 @@
1
1
  export { RunEvaluator, EvaluationResult } from "./evaluator.js";
2
2
  export { StringEvaluator, GradingFunctionParams, GradingFunctionResult, } from "./string_evaluator.js";
3
+ export { evaluate, type EvaluateOptions } from "./_runner.js";
@@ -1 +1,2 @@
1
1
  export { StringEvaluator, } from "./string_evaluator.js";
2
+ export { evaluate } from "./_runner.js";
package/dist/index.cjs CHANGED
@@ -6,4 +6,4 @@ Object.defineProperty(exports, "Client", { enumerable: true, get: function () {
6
6
  var run_trees_js_1 = require("./run_trees.cjs");
7
7
  Object.defineProperty(exports, "RunTree", { enumerable: true, get: function () { return run_trees_js_1.RunTree; } });
8
8
  // Update using yarn bump-version
9
- exports.__version__ = "0.1.21";
9
+ exports.__version__ = "0.1.22";
package/dist/index.d.ts CHANGED
@@ -1,4 +1,4 @@
1
1
  export { Client } from "./client.js";
2
2
  export type { Dataset, Example, TracerSession, Run, Feedback, } from "./schemas.js";
3
3
  export { RunTree, type RunTreeConfig } from "./run_trees.js";
4
- export declare const __version__ = "0.1.21";
4
+ export declare const __version__ = "0.1.22";
package/dist/index.js CHANGED
@@ -1,4 +1,4 @@
1
1
  export { Client } from "./client.js";
2
2
  export { RunTree } from "./run_trees.js";
3
3
  // Update using yarn bump-version
4
- export const __version__ = "0.1.21";
4
+ export const __version__ = "0.1.22";
@@ -20,6 +20,7 @@ export interface RunTreeConfig {
20
20
  outputs?: KVMap;
21
21
  reference_example_id?: string;
22
22
  client?: Client;
23
+ on_end?: (runTree: RunTree) => void;
23
24
  }
24
25
  export interface RunnableConfigLike {
25
26
  /**
package/dist/schemas.d.ts CHANGED
@@ -5,6 +5,9 @@ export interface TracerSession {
5
5
  end_time?: number;
6
6
  description?: string;
7
7
  name?: string;
8
+ /** Extra metadata for the project. */
9
+ extra?: KVMap;
10
+ reference_dataset_id?: string;
8
11
  }
9
12
  export interface TracerSessionResult extends TracerSession {
10
13
  run_count?: number;
@@ -15,7 +18,6 @@ export interface TracerSessionResult extends TracerSession {
15
18
  completion_tokens?: number;
16
19
  last_run_start_time?: number;
17
20
  feedback_stats?: Record<string, unknown>;
18
- reference_dataset_id?: string;
19
21
  run_facets?: KVMap[];
20
22
  }
21
23
  export type KVMap = Record<string, any>;
@@ -78,6 +80,14 @@ export interface BaseRun {
78
80
  */
79
81
  dotted_order?: string;
80
82
  }
83
+ type S3URL = {
84
+ ROOT: {
85
+ /** A pre-signed URL */
86
+ presigned_url: string;
87
+ /** The S3 path to the object in storage */
88
+ s3_url: string;
89
+ };
90
+ };
81
91
  /**
82
92
  * Describes properties of a run when loaded from the database.
83
93
  * Extends the BaseRun interface.
@@ -111,6 +121,10 @@ export interface Run extends BaseRun {
111
121
  parent_run_ids?: string[];
112
122
  /** Whether the run is included in a dataset. */
113
123
  in_dataset?: boolean;
124
+ /** The output S3 URLs */
125
+ outputs_s3_urls?: S3URL;
126
+ /** The input S3 URLs */
127
+ inputs_s3_urls?: S3URL;
114
128
  }
115
129
  export interface RunCreate extends BaseRun {
116
130
  revision_id?: string;
@@ -235,6 +249,9 @@ export interface FeedbackCategory {
235
249
  export interface FeedbackConfig {
236
250
  /**
237
251
  * The type of feedback.
252
+ * - "continuous": Feedback with a continuous numeric.
253
+ * - "categorical": Feedback with a categorical value (classes)
254
+ * - "freeform": Feedback with a freeform text value (notes).
238
255
  */
239
256
  type: "continuous" | "categorical" | "freeform";
240
257
  /**
@@ -246,6 +263,9 @@ export interface FeedbackConfig {
246
263
  */
247
264
  max?: number | null;
248
265
  /**
266
+ * The categories for categorical feedback.
267
+ * Each category can be a string or an object with additional properties.
268
+ *
249
269
  * If feedback is categorical, this defines the valid categories the server will accept.
250
270
  * Not applicable to continuous or freeform feedback types.
251
271
  */
@@ -256,3 +276,4 @@ export interface DatasetDiffInfo {
256
276
  examples_added: string[];
257
277
  examples_removed: string[];
258
278
  }
279
+ export {};
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.isTraceableFunction = exports.getCurrentRunTree = exports.traceable = void 0;
3
+ exports.wrapFunctionAndEnsureTraceable = exports.isTraceableFunction = exports.getCurrentRunTree = exports.traceable = void 0;
4
4
  const async_hooks_1 = require("async_hooks");
5
5
  const run_trees_js_1 = require("./run_trees.cjs");
6
6
  const env_js_1 = require("./utils/env.cjs");
@@ -15,10 +15,21 @@ const isAsyncIterable = (x) => x != null &&
15
15
  typeof x === "object" &&
16
16
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
17
17
  typeof x[Symbol.asyncIterator] === "function";
18
- const getTracingRunTree = (runTree) => {
19
- const tracingEnabled = (0, env_js_1.getEnvironmentVariable)("LANGSMITH_TRACING_V2") === "true" ||
20
- (0, env_js_1.getEnvironmentVariable)("LANGCHAIN_TRACING_V2") === "true";
21
- if (!tracingEnabled) {
18
+ const tracingIsEnabled = (tracingEnabled) => {
19
+ if (tracingEnabled !== undefined) {
20
+ return tracingEnabled;
21
+ }
22
+ const envVars = [
23
+ "LANGSMITH_TRACING_V2",
24
+ "LANGCHAIN_TRACING_V2",
25
+ "LANGSMITH_TRACING",
26
+ "LANGCHAIN_TRACING",
27
+ ];
28
+ return Boolean(envVars.find((envVar) => (0, env_js_1.getEnvironmentVariable)(envVar) === "true"));
29
+ };
30
+ const getTracingRunTree = (runTree, tracingEnabled) => {
31
+ const tracingEnabled_ = tracingIsEnabled(tracingEnabled);
32
+ if (!tracingEnabled_) {
22
33
  return undefined;
23
34
  }
24
35
  return runTree;
@@ -39,7 +50,7 @@ const getTracingRunTree = (runTree) => {
39
50
  */
40
51
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
41
52
  function traceable(wrappedFunc, config) {
42
- const { aggregator, argsConfigPath, ...runTreeConfig } = config ?? {};
53
+ const { aggregator, argsConfigPath, tracingEnabled, ...runTreeConfig } = config ?? {};
43
54
  const traceableFunc = (...args) => {
44
55
  let currentRunTree;
45
56
  let rawInputs;
@@ -105,7 +116,7 @@ function traceable(wrappedFunc, config) {
105
116
  currentRunTree = new run_trees_js_1.RunTree(ensuredConfig);
106
117
  rawInputs = args;
107
118
  }
108
- currentRunTree = getTracingRunTree(currentRunTree);
119
+ currentRunTree = getTracingRunTree(currentRunTree, tracingEnabled);
109
120
  let inputs;
110
121
  const firstInput = rawInputs[0];
111
122
  if (firstInput == null) {
@@ -173,6 +184,15 @@ function traceable(wrappedFunc, config) {
173
184
  else {
174
185
  await currentRunTree?.end({ outputs: finalOutputs });
175
186
  }
187
+ const onEnd = config?.on_end;
188
+ if (onEnd) {
189
+ if (!currentRunTree) {
190
+ console.warn("Can not call 'on_end' if currentRunTree is undefined");
191
+ }
192
+ else {
193
+ onEnd(currentRunTree);
194
+ }
195
+ }
176
196
  await postRunPromise;
177
197
  await currentRunTree?.patchRun();
178
198
  }
@@ -225,6 +245,15 @@ function traceable(wrappedFunc, config) {
225
245
  else {
226
246
  await currentRunTree?.end({ outputs: finalOutputs });
227
247
  }
248
+ const onEnd = config?.on_end;
249
+ if (onEnd) {
250
+ if (!currentRunTree) {
251
+ console.warn("Can not call 'on_end' if currentRunTree is undefined");
252
+ }
253
+ else {
254
+ onEnd(currentRunTree);
255
+ }
256
+ }
228
257
  await postRunPromise;
229
258
  await currentRunTree?.patchRun();
230
259
  }
@@ -234,6 +263,15 @@ function traceable(wrappedFunc, config) {
234
263
  else {
235
264
  try {
236
265
  await currentRunTree?.end(isKVMap(rawOutput) ? rawOutput : { outputs: rawOutput });
266
+ const onEnd = config?.on_end;
267
+ if (onEnd) {
268
+ if (!currentRunTree) {
269
+ console.warn("Can not call 'on_end' if currentRunTree is undefined");
270
+ }
271
+ else {
272
+ onEnd(currentRunTree);
273
+ }
274
+ }
237
275
  await postRunPromise;
238
276
  await currentRunTree?.patchRun();
239
277
  }
@@ -246,6 +284,15 @@ function traceable(wrappedFunc, config) {
246
284
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
247
285
  async (error) => {
248
286
  await currentRunTree?.end(undefined, String(error));
287
+ const onEnd = config?.on_end;
288
+ if (onEnd) {
289
+ if (!currentRunTree) {
290
+ console.warn("Can not call 'on_end' if currentRunTree is undefined");
291
+ }
292
+ else {
293
+ onEnd(currentRunTree);
294
+ }
295
+ }
249
296
  await postRunPromise;
250
297
  await currentRunTree?.patchRun();
251
298
  throw error;
@@ -302,3 +349,13 @@ function isKVMap(x) {
302
349
  // eslint-disable-next-line no-instanceof/no-instanceof
303
350
  !(x instanceof Date));
304
351
  }
352
+ function wrapFunctionAndEnsureTraceable(target, options, name = "target") {
353
+ if (typeof target === "function") {
354
+ return traceable(target, {
355
+ ...options,
356
+ name,
357
+ });
358
+ }
359
+ throw new Error("Target must be runnable function");
360
+ }
361
+ exports.wrapFunctionAndEnsureTraceable = wrapFunctionAndEnsureTraceable;
@@ -48,6 +48,7 @@ export type TraceableFunction<Func extends (...args: any[]) => any> = Func exten
48
48
  export declare function traceable<Func extends (...args: any[]) => any>(wrappedFunc: Func, config?: Partial<RunTreeConfig> & {
49
49
  aggregator?: (args: any[]) => any;
50
50
  argsConfigPath?: [number] | [number, string];
51
+ tracingEnabled?: boolean;
51
52
  }): TraceableFunction<Func>;
52
53
  /**
53
54
  * Return the current run tree from within a traceable-wrapped function.
@@ -57,4 +58,5 @@ export declare function traceable<Func extends (...args: any[]) => any>(wrappedF
57
58
  */
58
59
  export declare function getCurrentRunTree(): RunTree;
59
60
  export declare function isTraceableFunction(x: unknown): x is TraceableFunction<any>;
61
+ export declare function wrapFunctionAndEnsureTraceable<Func extends (...args: any[]) => any>(target: Func, options: Partial<RunTreeConfig>, name?: string): TraceableFunction<Func>;
60
62
  export {};
package/dist/traceable.js CHANGED
@@ -12,10 +12,21 @@ const isAsyncIterable = (x) => x != null &&
12
12
  typeof x === "object" &&
13
13
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
14
14
  typeof x[Symbol.asyncIterator] === "function";
15
- const getTracingRunTree = (runTree) => {
16
- const tracingEnabled = getEnvironmentVariable("LANGSMITH_TRACING_V2") === "true" ||
17
- getEnvironmentVariable("LANGCHAIN_TRACING_V2") === "true";
18
- if (!tracingEnabled) {
15
+ const tracingIsEnabled = (tracingEnabled) => {
16
+ if (tracingEnabled !== undefined) {
17
+ return tracingEnabled;
18
+ }
19
+ const envVars = [
20
+ "LANGSMITH_TRACING_V2",
21
+ "LANGCHAIN_TRACING_V2",
22
+ "LANGSMITH_TRACING",
23
+ "LANGCHAIN_TRACING",
24
+ ];
25
+ return Boolean(envVars.find((envVar) => getEnvironmentVariable(envVar) === "true"));
26
+ };
27
+ const getTracingRunTree = (runTree, tracingEnabled) => {
28
+ const tracingEnabled_ = tracingIsEnabled(tracingEnabled);
29
+ if (!tracingEnabled_) {
19
30
  return undefined;
20
31
  }
21
32
  return runTree;
@@ -36,7 +47,7 @@ const getTracingRunTree = (runTree) => {
36
47
  */
37
48
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
38
49
  export function traceable(wrappedFunc, config) {
39
- const { aggregator, argsConfigPath, ...runTreeConfig } = config ?? {};
50
+ const { aggregator, argsConfigPath, tracingEnabled, ...runTreeConfig } = config ?? {};
40
51
  const traceableFunc = (...args) => {
41
52
  let currentRunTree;
42
53
  let rawInputs;
@@ -102,7 +113,7 @@ export function traceable(wrappedFunc, config) {
102
113
  currentRunTree = new RunTree(ensuredConfig);
103
114
  rawInputs = args;
104
115
  }
105
- currentRunTree = getTracingRunTree(currentRunTree);
116
+ currentRunTree = getTracingRunTree(currentRunTree, tracingEnabled);
106
117
  let inputs;
107
118
  const firstInput = rawInputs[0];
108
119
  if (firstInput == null) {
@@ -170,6 +181,15 @@ export function traceable(wrappedFunc, config) {
170
181
  else {
171
182
  await currentRunTree?.end({ outputs: finalOutputs });
172
183
  }
184
+ const onEnd = config?.on_end;
185
+ if (onEnd) {
186
+ if (!currentRunTree) {
187
+ console.warn("Can not call 'on_end' if currentRunTree is undefined");
188
+ }
189
+ else {
190
+ onEnd(currentRunTree);
191
+ }
192
+ }
173
193
  await postRunPromise;
174
194
  await currentRunTree?.patchRun();
175
195
  }
@@ -222,6 +242,15 @@ export function traceable(wrappedFunc, config) {
222
242
  else {
223
243
  await currentRunTree?.end({ outputs: finalOutputs });
224
244
  }
245
+ const onEnd = config?.on_end;
246
+ if (onEnd) {
247
+ if (!currentRunTree) {
248
+ console.warn("Can not call 'on_end' if currentRunTree is undefined");
249
+ }
250
+ else {
251
+ onEnd(currentRunTree);
252
+ }
253
+ }
225
254
  await postRunPromise;
226
255
  await currentRunTree?.patchRun();
227
256
  }
@@ -231,6 +260,15 @@ export function traceable(wrappedFunc, config) {
231
260
  else {
232
261
  try {
233
262
  await currentRunTree?.end(isKVMap(rawOutput) ? rawOutput : { outputs: rawOutput });
263
+ const onEnd = config?.on_end;
264
+ if (onEnd) {
265
+ if (!currentRunTree) {
266
+ console.warn("Can not call 'on_end' if currentRunTree is undefined");
267
+ }
268
+ else {
269
+ onEnd(currentRunTree);
270
+ }
271
+ }
234
272
  await postRunPromise;
235
273
  await currentRunTree?.patchRun();
236
274
  }
@@ -243,6 +281,15 @@ export function traceable(wrappedFunc, config) {
243
281
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
244
282
  async (error) => {
245
283
  await currentRunTree?.end(undefined, String(error));
284
+ const onEnd = config?.on_end;
285
+ if (onEnd) {
286
+ if (!currentRunTree) {
287
+ console.warn("Can not call 'on_end' if currentRunTree is undefined");
288
+ }
289
+ else {
290
+ onEnd(currentRunTree);
291
+ }
292
+ }
246
293
  await postRunPromise;
247
294
  await currentRunTree?.patchRun();
248
295
  throw error;
@@ -296,3 +343,12 @@ function isKVMap(x) {
296
343
  // eslint-disable-next-line no-instanceof/no-instanceof
297
344
  !(x instanceof Date));
298
345
  }
346
+ export function wrapFunctionAndEnsureTraceable(target, options, name = "target") {
347
+ if (typeof target === "function") {
348
+ return traceable(target, {
349
+ ...options,
350
+ name,
351
+ });
352
+ }
353
+ throw new Error("Target must be runnable function");
354
+ }