langsmith 0.1.14 → 0.1.19

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.
package/client.d.cts ADDED
@@ -0,0 +1 @@
1
+ export * from './dist/client.js'
package/dist/client.cjs CHANGED
@@ -777,7 +777,7 @@ class Client {
777
777
  * @param traceId - The ID of the trace to filter by.
778
778
  * @param referenceExampleId - The ID of the reference example to filter by.
779
779
  * @param startTime - The start time to filter by.
780
- * @param executionOrder - The execution order to filter by.
780
+ * @param isRoot - Indicates whether to only return root runs.
781
781
  * @param runType - The run type to filter by.
782
782
  * @param error - Indicates whether to filter by error runs.
783
783
  * @param id - The ID of the run to filter by.
@@ -851,7 +851,7 @@ class Client {
851
851
  * });
852
852
  */
853
853
  async *listRuns(props) {
854
- const { projectId, projectName, parentRunId, traceId, referenceExampleId, startTime, executionOrder, runType, error, id, query, filter, traceFilter, treeFilter, limit, } = props;
854
+ const { projectId, projectName, parentRunId, traceId, referenceExampleId, startTime, executionOrder, isRoot, runType, error, id, query, filter, traceFilter, treeFilter, limit, select, } = props;
855
855
  let projectIds = [];
856
856
  if (projectId) {
857
857
  projectIds = Array.isArray(projectId) ? projectId : [projectId];
@@ -863,6 +863,36 @@ class Client {
863
863
  const projectIds_ = await Promise.all(projectNames.map((name) => this.readProject({ projectName: name }).then((project) => project.id)));
864
864
  projectIds.push(...projectIds_);
865
865
  }
866
+ const default_select = [
867
+ "app_path",
868
+ "child_run_ids",
869
+ "completion_cost",
870
+ "completion_tokens",
871
+ "dotted_order",
872
+ "end_time",
873
+ "error",
874
+ "events",
875
+ "extra",
876
+ "feedback_stats",
877
+ "first_token_time",
878
+ "id",
879
+ "inputs",
880
+ "name",
881
+ "outputs",
882
+ "parent_run_id",
883
+ "parent_run_ids",
884
+ "prompt_cost",
885
+ "prompt_tokens",
886
+ "reference_example_id",
887
+ "run_type",
888
+ "session_id",
889
+ "start_time",
890
+ "status",
891
+ "tags",
892
+ "total_cost",
893
+ "total_tokens",
894
+ "trace_id",
895
+ ];
866
896
  const body = {
867
897
  session: projectIds.length ? projectIds : null,
868
898
  run_type: runType,
@@ -878,6 +908,8 @@ class Client {
878
908
  id,
879
909
  limit,
880
910
  trace: traceId,
911
+ select: select ? select : default_select,
912
+ is_root: isRoot,
881
913
  };
882
914
  for await (const runs of this._getCursorPaginatedList("/runs/query", body)) {
883
915
  yield* runs;
@@ -1377,7 +1409,7 @@ class Client {
1377
1409
  }
1378
1410
  await response.json();
1379
1411
  }
1380
- async createExample(inputs, outputs, { datasetId, datasetName, createdAt, exampleId }) {
1412
+ async createExample(inputs, outputs, { datasetId, datasetName, createdAt, exampleId, metadata, }) {
1381
1413
  let datasetId_ = datasetId;
1382
1414
  if (datasetId_ === undefined && datasetName === undefined) {
1383
1415
  throw new Error("Must provide either datasetName or datasetId");
@@ -1396,6 +1428,7 @@ class Client {
1396
1428
  outputs,
1397
1429
  created_at: createdAt_?.toISOString(),
1398
1430
  id: exampleId,
1431
+ metadata,
1399
1432
  };
1400
1433
  const response = await this.caller.call(fetch, `${this.apiUrl}/examples`, {
1401
1434
  method: "POST",
@@ -1411,7 +1444,7 @@ class Client {
1411
1444
  return result;
1412
1445
  }
1413
1446
  async createExamples(props) {
1414
- const { inputs, outputs, sourceRunIds, exampleIds, datasetId, datasetName, } = props;
1447
+ const { inputs, outputs, metadata, sourceRunIds, exampleIds, datasetId, datasetName, } = props;
1415
1448
  let datasetId_ = datasetId;
1416
1449
  if (datasetId_ === undefined && datasetName === undefined) {
1417
1450
  throw new Error("Must provide either datasetName or datasetId");
@@ -1428,6 +1461,7 @@ class Client {
1428
1461
  dataset_id: datasetId_,
1429
1462
  inputs: input,
1430
1463
  outputs: outputs ? outputs[idx] : undefined,
1464
+ metadata: metadata ? metadata[idx] : undefined,
1431
1465
  id: exampleIds ? exampleIds[idx] : undefined,
1432
1466
  source_run_id: sourceRunIds ? sourceRunIds[idx] : undefined,
1433
1467
  };
package/dist/client.d.ts CHANGED
@@ -29,6 +29,10 @@ interface ListRunsParams {
29
29
  * The ID of the trace to filter by.
30
30
  */
31
31
  traceId?: string;
32
+ /**
33
+ * isRoot - Whether to only include root runs.
34
+ * */
35
+ isRoot?: boolean;
32
36
  /**
33
37
  * The execution order to filter by.
34
38
  */
@@ -96,6 +100,11 @@ interface ListRunsParams {
96
100
  * conjunction with the regular `filter` parameter to let you filter runs by attributes of any run within a trace.
97
101
  */
98
102
  treeFilter?: string;
103
+ /**
104
+ * The values to include in the response.
105
+ *
106
+ */
107
+ select?: string[];
99
108
  }
100
109
  interface UploadCSVParams {
101
110
  csvFile: Blob;
@@ -135,6 +144,7 @@ export type CreateExampleOptions = {
135
144
  datasetName?: string;
136
145
  createdAt?: Date;
137
146
  exampleId?: string;
147
+ metadata?: KVMap;
138
148
  };
139
149
  export declare class Queue<T> {
140
150
  items: [T, () => void][];
@@ -214,7 +224,7 @@ export declare class Client {
214
224
  * @param traceId - The ID of the trace to filter by.
215
225
  * @param referenceExampleId - The ID of the reference example to filter by.
216
226
  * @param startTime - The start time to filter by.
217
- * @param executionOrder - The execution order to filter by.
227
+ * @param isRoot - Indicates whether to only return root runs.
218
228
  * @param runType - The run type to filter by.
219
229
  * @param error - Indicates whether to filter by error runs.
220
230
  * @param id - The ID of the run to filter by.
@@ -367,10 +377,11 @@ export declare class Client {
367
377
  datasetId?: string;
368
378
  datasetName?: string;
369
379
  }): Promise<void>;
370
- createExample(inputs: KVMap, outputs: KVMap, { datasetId, datasetName, createdAt, exampleId }: CreateExampleOptions): Promise<Example>;
380
+ createExample(inputs: KVMap, outputs: KVMap, { datasetId, datasetName, createdAt, exampleId, metadata, }: CreateExampleOptions): Promise<Example>;
371
381
  createExamples(props: {
372
382
  inputs: Array<KVMap>;
373
383
  outputs?: Array<KVMap>;
384
+ metadata?: Array<KVMap>;
374
385
  sourceRunIds?: Array<string>;
375
386
  exampleIds?: Array<string>;
376
387
  datasetId?: string;
package/dist/client.js CHANGED
@@ -750,7 +750,7 @@ export class Client {
750
750
  * @param traceId - The ID of the trace to filter by.
751
751
  * @param referenceExampleId - The ID of the reference example to filter by.
752
752
  * @param startTime - The start time to filter by.
753
- * @param executionOrder - The execution order to filter by.
753
+ * @param isRoot - Indicates whether to only return root runs.
754
754
  * @param runType - The run type to filter by.
755
755
  * @param error - Indicates whether to filter by error runs.
756
756
  * @param id - The ID of the run to filter by.
@@ -824,7 +824,7 @@ export class Client {
824
824
  * });
825
825
  */
826
826
  async *listRuns(props) {
827
- const { projectId, projectName, parentRunId, traceId, referenceExampleId, startTime, executionOrder, runType, error, id, query, filter, traceFilter, treeFilter, limit, } = props;
827
+ const { projectId, projectName, parentRunId, traceId, referenceExampleId, startTime, executionOrder, isRoot, runType, error, id, query, filter, traceFilter, treeFilter, limit, select, } = props;
828
828
  let projectIds = [];
829
829
  if (projectId) {
830
830
  projectIds = Array.isArray(projectId) ? projectId : [projectId];
@@ -836,6 +836,36 @@ export class Client {
836
836
  const projectIds_ = await Promise.all(projectNames.map((name) => this.readProject({ projectName: name }).then((project) => project.id)));
837
837
  projectIds.push(...projectIds_);
838
838
  }
839
+ const default_select = [
840
+ "app_path",
841
+ "child_run_ids",
842
+ "completion_cost",
843
+ "completion_tokens",
844
+ "dotted_order",
845
+ "end_time",
846
+ "error",
847
+ "events",
848
+ "extra",
849
+ "feedback_stats",
850
+ "first_token_time",
851
+ "id",
852
+ "inputs",
853
+ "name",
854
+ "outputs",
855
+ "parent_run_id",
856
+ "parent_run_ids",
857
+ "prompt_cost",
858
+ "prompt_tokens",
859
+ "reference_example_id",
860
+ "run_type",
861
+ "session_id",
862
+ "start_time",
863
+ "status",
864
+ "tags",
865
+ "total_cost",
866
+ "total_tokens",
867
+ "trace_id",
868
+ ];
839
869
  const body = {
840
870
  session: projectIds.length ? projectIds : null,
841
871
  run_type: runType,
@@ -851,6 +881,8 @@ export class Client {
851
881
  id,
852
882
  limit,
853
883
  trace: traceId,
884
+ select: select ? select : default_select,
885
+ is_root: isRoot,
854
886
  };
855
887
  for await (const runs of this._getCursorPaginatedList("/runs/query", body)) {
856
888
  yield* runs;
@@ -1350,7 +1382,7 @@ export class Client {
1350
1382
  }
1351
1383
  await response.json();
1352
1384
  }
1353
- async createExample(inputs, outputs, { datasetId, datasetName, createdAt, exampleId }) {
1385
+ async createExample(inputs, outputs, { datasetId, datasetName, createdAt, exampleId, metadata, }) {
1354
1386
  let datasetId_ = datasetId;
1355
1387
  if (datasetId_ === undefined && datasetName === undefined) {
1356
1388
  throw new Error("Must provide either datasetName or datasetId");
@@ -1369,6 +1401,7 @@ export class Client {
1369
1401
  outputs,
1370
1402
  created_at: createdAt_?.toISOString(),
1371
1403
  id: exampleId,
1404
+ metadata,
1372
1405
  };
1373
1406
  const response = await this.caller.call(fetch, `${this.apiUrl}/examples`, {
1374
1407
  method: "POST",
@@ -1384,7 +1417,7 @@ export class Client {
1384
1417
  return result;
1385
1418
  }
1386
1419
  async createExamples(props) {
1387
- const { inputs, outputs, sourceRunIds, exampleIds, datasetId, datasetName, } = props;
1420
+ const { inputs, outputs, metadata, sourceRunIds, exampleIds, datasetId, datasetName, } = props;
1388
1421
  let datasetId_ = datasetId;
1389
1422
  if (datasetId_ === undefined && datasetName === undefined) {
1390
1423
  throw new Error("Must provide either datasetName or datasetId");
@@ -1401,6 +1434,7 @@ export class Client {
1401
1434
  dataset_id: datasetId_,
1402
1435
  inputs: input,
1403
1436
  outputs: outputs ? outputs[idx] : undefined,
1437
+ metadata: metadata ? metadata[idx] : undefined,
1404
1438
  id: exampleIds ? exampleIds[idx] : undefined,
1405
1439
  source_run_id: sourceRunIds ? sourceRunIds[idx] : undefined,
1406
1440
  };
@@ -1,4 +1,42 @@
1
1
  import { Example, Run, ScoreType, ValueType } from "../schemas.js";
2
+ /**
3
+ * Represents a categorical class.
4
+ */
5
+ export type Category = {
6
+ /**
7
+ * The value of the category.
8
+ */
9
+ value?: number;
10
+ /**
11
+ * The label of the category.
12
+ */
13
+ label: string;
14
+ };
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
+ };
2
40
  /**
3
41
  * Represents the result of an evaluation.
4
42
  */
@@ -38,6 +76,12 @@ export type EvaluationResult = {
38
76
  * the root of the trace.
39
77
  */
40
78
  targetRunId?: string;
79
+ /**
80
+ * The feedback config associated with the evaluation result.
81
+ * If set, this will be used to define how a feedback key
82
+ * should be interpreted.
83
+ */
84
+ feedbackConfig?: FeedbackConfig;
41
85
  };
42
86
  export interface RunEvaluator {
43
87
  evaluateRun(run: Run, example?: Example): Promise<EvaluationResult>;
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.14";
9
+ exports.__version__ = "0.1.19";
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.14";
4
+ export declare const __version__ = "0.1.19";
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.14";
4
+ export const __version__ = "0.1.19";
@@ -43,7 +43,7 @@ function convertToDottedOrderFormat(epoch, runId) {
43
43
  }
44
44
  exports.convertToDottedOrderFormat = convertToDottedOrderFormat;
45
45
  class RunTree {
46
- constructor(config) {
46
+ constructor(originalConfig) {
47
47
  Object.defineProperty(this, "id", {
48
48
  enumerable: true,
49
49
  configurable: true,
@@ -159,7 +159,13 @@ class RunTree {
159
159
  value: void 0
160
160
  });
161
161
  const defaultConfig = RunTree.getDefaultConfig();
162
+ const { metadata, ...config } = originalConfig;
162
163
  const client = config.client ?? new client_js_1.Client();
164
+ const dedupedMetadata = {
165
+ ...metadata,
166
+ ...config?.extra?.metadata,
167
+ };
168
+ config.extra = { ...config.extra, metadata: dedupedMetadata };
163
169
  Object.assign(this, { ...defaultConfig, ...config, client });
164
170
  if (!this.trace_id) {
165
171
  if (this.parent_run) {
@@ -191,7 +197,7 @@ class RunTree {
191
197
  parentRun = langChainTracer?.getRun?.(parentRunId);
192
198
  projectName = langChainTracer?.projectName;
193
199
  }
194
- const deduppedTags = [
200
+ const dedupedTags = [
195
201
  ...new Set((parentRun?.tags ?? []).concat(config?.tags ?? [])),
196
202
  ];
197
203
  const dedupedMetadata = {
@@ -201,7 +207,7 @@ class RunTree {
201
207
  const rt = new RunTree({
202
208
  name: props?.name ?? "<lambda>",
203
209
  parent_run: parentRun,
204
- tags: deduppedTags,
210
+ tags: dedupedTags,
205
211
  extra: {
206
212
  metadata: dedupedMetadata,
207
213
  },
@@ -12,6 +12,7 @@ export interface RunTreeConfig {
12
12
  start_time?: number;
13
13
  end_time?: number;
14
14
  extra?: KVMap;
15
+ metadata?: KVMap;
15
16
  tags?: string[];
16
17
  error?: string;
17
18
  serialized?: object;
@@ -57,7 +58,7 @@ export declare class RunTree implements BaseRun {
57
58
  events?: KVMap[] | undefined;
58
59
  trace_id: string;
59
60
  dotted_order: string;
60
- constructor(config: RunTreeConfig);
61
+ constructor(originalConfig: RunTreeConfig);
61
62
  static fromRunnableConfig(config: RunnableConfigLike, props: {
62
63
  name: string;
63
64
  tags?: string[];
package/dist/run_trees.js CHANGED
@@ -16,7 +16,7 @@ export function convertToDottedOrderFormat(epoch, runId) {
16
16
  runId);
17
17
  }
18
18
  export class RunTree {
19
- constructor(config) {
19
+ constructor(originalConfig) {
20
20
  Object.defineProperty(this, "id", {
21
21
  enumerable: true,
22
22
  configurable: true,
@@ -132,7 +132,13 @@ export class RunTree {
132
132
  value: void 0
133
133
  });
134
134
  const defaultConfig = RunTree.getDefaultConfig();
135
+ const { metadata, ...config } = originalConfig;
135
136
  const client = config.client ?? new Client();
137
+ const dedupedMetadata = {
138
+ ...metadata,
139
+ ...config?.extra?.metadata,
140
+ };
141
+ config.extra = { ...config.extra, metadata: dedupedMetadata };
136
142
  Object.assign(this, { ...defaultConfig, ...config, client });
137
143
  if (!this.trace_id) {
138
144
  if (this.parent_run) {
@@ -164,7 +170,7 @@ export class RunTree {
164
170
  parentRun = langChainTracer?.getRun?.(parentRunId);
165
171
  projectName = langChainTracer?.projectName;
166
172
  }
167
- const deduppedTags = [
173
+ const dedupedTags = [
168
174
  ...new Set((parentRun?.tags ?? []).concat(config?.tags ?? [])),
169
175
  ];
170
176
  const dedupedMetadata = {
@@ -174,7 +180,7 @@ export class RunTree {
174
180
  const rt = new RunTree({
175
181
  name: props?.name ?? "<lambda>",
176
182
  parent_run: parentRun,
177
- tags: deduppedTags,
183
+ tags: dedupedTags,
178
184
  extra: {
179
185
  metadata: dedupedMetadata,
180
186
  },
package/dist/schemas.d.ts CHANGED
@@ -15,7 +15,7 @@ export interface TracerSessionResult extends TracerSession {
15
15
  completion_tokens?: number;
16
16
  last_run_start_time?: number;
17
17
  feedback_stats?: Record<string, unknown>;
18
- reference_dataset_ids?: string[];
18
+ reference_dataset_id?: string;
19
19
  run_facets?: KVMap[];
20
20
  }
21
21
  export type KVMap = Record<string, any>;
@@ -27,6 +27,7 @@ export interface BaseExample {
27
27
  dataset_id: string;
28
28
  inputs: KVMap;
29
29
  outputs?: KVMap;
30
+ metadata?: KVMap;
30
31
  }
31
32
  /**
32
33
  * A run can represent either a trace (root run)
@@ -108,6 +109,8 @@ export interface Run extends BaseRun {
108
109
  first_token_time?: number;
109
110
  /** IDs of parent runs, if multiple exist. */
110
111
  parent_run_ids?: string[];
112
+ /** Whether the run is included in a dataset. */
113
+ in_dataset?: boolean;
111
114
  }
112
115
  export interface RunCreate extends BaseRun {
113
116
  revision_id?: string;
@@ -157,6 +160,7 @@ export interface ExampleUpdate {
157
160
  dataset_id?: string;
158
161
  inputs?: KVMap;
159
162
  outputs?: KVMap;
163
+ metadata?: KVMap;
160
164
  }
161
165
  export interface BaseDataset {
162
166
  name: string;
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.isTraceableFunction = exports.traceable = void 0;
3
+ 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 asyncLocalStorage = new async_hooks_1.AsyncLocalStorage();
@@ -24,12 +24,13 @@ const isAsyncIterable = (x) => x != null &&
24
24
  */
25
25
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
26
26
  function traceable(wrappedFunc, config) {
27
+ const { aggregator, ...runTreeConfig } = config ?? {};
27
28
  const traceableFunc = async (...args) => {
28
29
  let currentRunTree;
29
30
  let rawInputs;
30
31
  const ensuredConfig = {
31
32
  name: wrappedFunc.name || "<lambda>",
32
- ...config,
33
+ ...runTreeConfig,
33
34
  };
34
35
  const previousRunTree = asyncLocalStorage.getStore();
35
36
  if ((0, run_trees_js_1.isRunTree)(args[0])) {
@@ -79,7 +80,26 @@ function traceable(wrappedFunc, config) {
79
80
  chunks.push(chunk);
80
81
  yield chunk;
81
82
  }
82
- await currentRunTree.end({ outputs: chunks });
83
+ let finalOutputs;
84
+ if (aggregator !== undefined) {
85
+ try {
86
+ finalOutputs = await aggregator(chunks);
87
+ }
88
+ catch (e) {
89
+ console.error(`[ERROR]: LangSmith aggregation failed: `, e);
90
+ finalOutputs = chunks;
91
+ }
92
+ }
93
+ else {
94
+ finalOutputs = chunks;
95
+ }
96
+ if (typeof finalOutputs === "object" &&
97
+ !Array.isArray(finalOutputs)) {
98
+ await currentRunTree.end(finalOutputs);
99
+ }
100
+ else {
101
+ await currentRunTree.end({ outputs: finalOutputs });
102
+ }
83
103
  await currentRunTree.patchRun();
84
104
  }
85
105
  return resolve(wrapOutputForTracing());
@@ -112,11 +132,29 @@ function traceable(wrappedFunc, config) {
112
132
  });
113
133
  };
114
134
  Object.defineProperty(traceableFunc, "langsmith:traceable", {
115
- value: config,
135
+ value: runTreeConfig,
116
136
  });
117
137
  return traceableFunc;
118
138
  }
119
139
  exports.traceable = traceable;
140
+ /**
141
+ * Return the current run tree from within a traceable-wrapped function.
142
+ * Will throw an error if called outside of a traceable function.
143
+ *
144
+ * @returns The run tree for the given context.
145
+ */
146
+ function getCurrentRunTree() {
147
+ const runTree = asyncLocalStorage.getStore();
148
+ if (runTree === undefined) {
149
+ throw new Error([
150
+ "Could not get the current run tree.",
151
+ "",
152
+ "Please make sure you are calling this method within a traceable function.",
153
+ ].join("\n"));
154
+ }
155
+ return runTree;
156
+ }
157
+ exports.getCurrentRunTree = getCurrentRunTree;
120
158
  function isTraceableFunction(x
121
159
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
122
160
  ) {
@@ -44,6 +44,15 @@ export type TraceableFunction<Func extends (...args: any[]) => any> = Func exten
44
44
  * @param config Additional metadata such as name, tags or providing
45
45
  * a custom LangSmith client instance
46
46
  */
47
- export declare function traceable<Func extends (...args: any[]) => any>(wrappedFunc: Func, config?: Partial<RunTreeConfig>): TraceableFunction<Func>;
47
+ export declare function traceable<Func extends (...args: any[]) => any>(wrappedFunc: Func, config?: Partial<RunTreeConfig> & {
48
+ aggregator?: (args: any[]) => any;
49
+ }): TraceableFunction<Func>;
50
+ /**
51
+ * Return the current run tree from within a traceable-wrapped function.
52
+ * Will throw an error if called outside of a traceable function.
53
+ *
54
+ * @returns The run tree for the given context.
55
+ */
56
+ export declare function getCurrentRunTree(): RunTree;
48
57
  export declare function isTraceableFunction(x: unknown): x is TraceableFunction<any>;
49
58
  export {};
package/dist/traceable.js CHANGED
@@ -21,12 +21,13 @@ const isAsyncIterable = (x) => x != null &&
21
21
  */
22
22
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
23
23
  export function traceable(wrappedFunc, config) {
24
+ const { aggregator, ...runTreeConfig } = config ?? {};
24
25
  const traceableFunc = async (...args) => {
25
26
  let currentRunTree;
26
27
  let rawInputs;
27
28
  const ensuredConfig = {
28
29
  name: wrappedFunc.name || "<lambda>",
29
- ...config,
30
+ ...runTreeConfig,
30
31
  };
31
32
  const previousRunTree = asyncLocalStorage.getStore();
32
33
  if (isRunTree(args[0])) {
@@ -76,7 +77,26 @@ export function traceable(wrappedFunc, config) {
76
77
  chunks.push(chunk);
77
78
  yield chunk;
78
79
  }
79
- await currentRunTree.end({ outputs: chunks });
80
+ let finalOutputs;
81
+ if (aggregator !== undefined) {
82
+ try {
83
+ finalOutputs = await aggregator(chunks);
84
+ }
85
+ catch (e) {
86
+ console.error(`[ERROR]: LangSmith aggregation failed: `, e);
87
+ finalOutputs = chunks;
88
+ }
89
+ }
90
+ else {
91
+ finalOutputs = chunks;
92
+ }
93
+ if (typeof finalOutputs === "object" &&
94
+ !Array.isArray(finalOutputs)) {
95
+ await currentRunTree.end(finalOutputs);
96
+ }
97
+ else {
98
+ await currentRunTree.end({ outputs: finalOutputs });
99
+ }
80
100
  await currentRunTree.patchRun();
81
101
  }
82
102
  return resolve(wrapOutputForTracing());
@@ -109,10 +129,27 @@ export function traceable(wrappedFunc, config) {
109
129
  });
110
130
  };
111
131
  Object.defineProperty(traceableFunc, "langsmith:traceable", {
112
- value: config,
132
+ value: runTreeConfig,
113
133
  });
114
134
  return traceableFunc;
115
135
  }
136
+ /**
137
+ * Return the current run tree from within a traceable-wrapped function.
138
+ * Will throw an error if called outside of a traceable function.
139
+ *
140
+ * @returns The run tree for the given context.
141
+ */
142
+ export function getCurrentRunTree() {
143
+ const runTree = asyncLocalStorage.getStore();
144
+ if (runTree === undefined) {
145
+ throw new Error([
146
+ "Could not get the current run tree.",
147
+ "",
148
+ "Please make sure you are calling this method within a traceable function.",
149
+ ].join("\n"));
150
+ }
151
+ return runTree;
152
+ }
116
153
  export function isTraceableFunction(x
117
154
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
118
155
  ) {
@@ -0,0 +1,17 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __exportStar = (this && this.__exportStar) || function(m, exports) {
14
+ for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
+ };
16
+ Object.defineProperty(exports, "__esModule", { value: true });
17
+ __exportStar(require("./openai.cjs"), exports);
@@ -0,0 +1 @@
1
+ export * from "./openai.js";
@@ -0,0 +1 @@
1
+ export * from "./openai.js";