langsmith 0.1.21 → 0.1.23-rc.0

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/dist/traceable.js CHANGED
@@ -8,16 +8,48 @@ function isPromiseMethod(x) {
8
8
  return false;
9
9
  }
10
10
  const asyncLocalStorage = new AsyncLocalStorage();
11
+ export const ROOT = Symbol("langsmith:traceable:root");
11
12
  const isAsyncIterable = (x) => x != null &&
12
13
  typeof x === "object" &&
13
14
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
14
15
  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) {
16
+ const tracingIsEnabled = (tracingEnabled) => {
17
+ if (tracingEnabled !== undefined) {
18
+ return tracingEnabled;
19
+ }
20
+ const envVars = [
21
+ "LANGSMITH_TRACING_V2",
22
+ "LANGCHAIN_TRACING_V2",
23
+ "LANGSMITH_TRACING",
24
+ "LANGCHAIN_TRACING",
25
+ ];
26
+ return Boolean(envVars.find((envVar) => getEnvironmentVariable(envVar) === "true"));
27
+ };
28
+ const handleRunInputs = (rawInputs) => {
29
+ const firstInput = rawInputs[0];
30
+ if (firstInput == null) {
31
+ return {};
32
+ }
33
+ if (rawInputs.length > 1) {
34
+ return { args: rawInputs };
35
+ }
36
+ if (isKVMap(firstInput)) {
37
+ return firstInput;
38
+ }
39
+ return { input: firstInput };
40
+ };
41
+ const handleRunOutputs = (rawOutputs) => {
42
+ if (isKVMap(rawOutputs)) {
43
+ return rawOutputs;
44
+ }
45
+ return { outputs: rawOutputs };
46
+ };
47
+ const getTracingRunTree = (runTree, inputs) => {
48
+ const tracingEnabled_ = tracingIsEnabled(runTree.tracingEnabled);
49
+ if (!tracingEnabled_) {
19
50
  return undefined;
20
51
  }
52
+ runTree.inputs = handleRunInputs(inputs);
21
53
  return runTree;
22
54
  };
23
55
  /**
@@ -38,8 +70,6 @@ const getTracingRunTree = (runTree) => {
38
70
  export function traceable(wrappedFunc, config) {
39
71
  const { aggregator, argsConfigPath, ...runTreeConfig } = config ?? {};
40
72
  const traceableFunc = (...args) => {
41
- let currentRunTree;
42
- let rawInputs;
43
73
  let ensuredConfig;
44
74
  try {
45
75
  let runtimeConfig;
@@ -85,41 +115,42 @@ export function traceable(wrappedFunc, config) {
85
115
  ...runTreeConfig,
86
116
  };
87
117
  }
88
- const previousRunTree = asyncLocalStorage.getStore();
89
- if (isRunTree(args[0])) {
90
- currentRunTree = args[0];
91
- rawInputs = args.slice(1);
92
- }
93
- else if (isRunnableConfigLike(args[0])) {
94
- currentRunTree = RunTree.fromRunnableConfig(args[0], ensuredConfig);
95
- rawInputs = args.slice(1);
96
- }
97
- else if (previousRunTree !== undefined) {
98
- currentRunTree = previousRunTree.createChild(ensuredConfig);
99
- rawInputs = args;
100
- }
101
- else {
102
- currentRunTree = new RunTree(ensuredConfig);
103
- rawInputs = args;
104
- }
105
- currentRunTree = getTracingRunTree(currentRunTree);
106
- let inputs;
107
- const firstInput = rawInputs[0];
108
- if (firstInput == null) {
109
- inputs = {};
110
- }
111
- else if (rawInputs.length > 1) {
112
- inputs = { args: rawInputs };
113
- }
114
- else if (isKVMap(firstInput)) {
115
- inputs = firstInput;
116
- }
117
- else {
118
- inputs = { input: firstInput };
119
- }
120
- if (currentRunTree) {
121
- currentRunTree.inputs = inputs;
122
- }
118
+ const [currentRunTree, rawInputs] = (() => {
119
+ const [firstArg, ...restArgs] = args;
120
+ // used for handoff between LangChain.JS and traceable functions
121
+ if (isRunnableConfigLike(firstArg)) {
122
+ return [
123
+ getTracingRunTree(RunTree.fromRunnableConfig(firstArg, ensuredConfig), restArgs),
124
+ restArgs,
125
+ ];
126
+ }
127
+ // legacy CallbackManagerRunTree used in runOnDataset
128
+ // override ALS and do not pass-through the run tree
129
+ if (isRunTree(firstArg) &&
130
+ "callbackManager" in firstArg &&
131
+ firstArg.callbackManager != null) {
132
+ return [firstArg, restArgs];
133
+ }
134
+ // when ALS is unreliable, users can manually
135
+ // pass in the run tree
136
+ if (firstArg === ROOT || isRunTree(firstArg)) {
137
+ const currentRunTree = getTracingRunTree(firstArg === ROOT
138
+ ? new RunTree(ensuredConfig)
139
+ : firstArg.createChild(ensuredConfig), restArgs);
140
+ return [currentRunTree, [currentRunTree, ...restArgs]];
141
+ }
142
+ // Node.JS uses AsyncLocalStorage (ALS) and AsyncResource
143
+ // to allow storing context
144
+ const prevRunFromStore = asyncLocalStorage.getStore();
145
+ if (prevRunFromStore) {
146
+ return [
147
+ getTracingRunTree(prevRunFromStore.createChild(ensuredConfig), args),
148
+ args,
149
+ ];
150
+ }
151
+ const currentRunTree = getTracingRunTree(new RunTree(ensuredConfig), args);
152
+ return [currentRunTree, args];
153
+ })();
123
154
  return asyncLocalStorage.run(currentRunTree, () => {
124
155
  const postRunPromise = currentRunTree?.postRun();
125
156
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
@@ -170,6 +201,15 @@ export function traceable(wrappedFunc, config) {
170
201
  else {
171
202
  await currentRunTree?.end({ outputs: finalOutputs });
172
203
  }
204
+ const onEnd = config?.on_end;
205
+ if (onEnd) {
206
+ if (!currentRunTree) {
207
+ console.warn("Can not call 'on_end' if currentRunTree is undefined");
208
+ }
209
+ else {
210
+ onEnd(currentRunTree);
211
+ }
212
+ }
173
213
  await postRunPromise;
174
214
  await currentRunTree?.patchRun();
175
215
  }
@@ -222,6 +262,15 @@ export function traceable(wrappedFunc, config) {
222
262
  else {
223
263
  await currentRunTree?.end({ outputs: finalOutputs });
224
264
  }
265
+ const onEnd = config?.on_end;
266
+ if (onEnd) {
267
+ if (!currentRunTree) {
268
+ console.warn("Can not call 'on_end' if currentRunTree is undefined");
269
+ }
270
+ else {
271
+ onEnd(currentRunTree);
272
+ }
273
+ }
225
274
  await postRunPromise;
226
275
  await currentRunTree?.patchRun();
227
276
  }
@@ -230,7 +279,16 @@ export function traceable(wrappedFunc, config) {
230
279
  }
231
280
  else {
232
281
  try {
233
- await currentRunTree?.end(isKVMap(rawOutput) ? rawOutput : { outputs: rawOutput });
282
+ await currentRunTree?.end(handleRunOutputs(rawOutput));
283
+ const onEnd = config?.on_end;
284
+ if (onEnd) {
285
+ if (!currentRunTree) {
286
+ console.warn("Can not call 'on_end' if currentRunTree is undefined");
287
+ }
288
+ else {
289
+ onEnd(currentRunTree);
290
+ }
291
+ }
234
292
  await postRunPromise;
235
293
  await currentRunTree?.patchRun();
236
294
  }
@@ -243,6 +301,15 @@ export function traceable(wrappedFunc, config) {
243
301
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
244
302
  async (error) => {
245
303
  await currentRunTree?.end(undefined, String(error));
304
+ const onEnd = config?.on_end;
305
+ if (onEnd) {
306
+ if (!currentRunTree) {
307
+ console.warn("Can not call 'on_end' if currentRunTree is undefined");
308
+ }
309
+ else {
310
+ onEnd(currentRunTree);
311
+ }
312
+ }
246
313
  await postRunPromise;
247
314
  await currentRunTree?.patchRun();
248
315
  throw error;
@@ -296,3 +363,12 @@ function isKVMap(x) {
296
363
  // eslint-disable-next-line no-instanceof/no-instanceof
297
364
  !(x instanceof Date));
298
365
  }
366
+ export function wrapFunctionAndEnsureTraceable(target, options, name = "target") {
367
+ if (typeof target === "function") {
368
+ return traceable(target, {
369
+ ...options,
370
+ name,
371
+ });
372
+ }
373
+ throw new Error("Target must be runnable function");
374
+ }
@@ -0,0 +1,72 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.getDefaultRevisionId = exports.getGitInfo = void 0;
4
+ async function importChildProcess() {
5
+ const { exec } = await import("child_process");
6
+ return { exec };
7
+ }
8
+ const execGit = (command, exec) => {
9
+ return new Promise((resolve) => {
10
+ exec(`git ${command.join(" ")}`, (error, stdout) => {
11
+ if (error) {
12
+ resolve(null);
13
+ }
14
+ else {
15
+ resolve(stdout.trim());
16
+ }
17
+ });
18
+ });
19
+ };
20
+ const getGitInfo = async (remote = "origin") => {
21
+ let exec;
22
+ try {
23
+ const execImport = await importChildProcess();
24
+ exec = execImport.exec;
25
+ }
26
+ catch (e) {
27
+ // no-op
28
+ return null;
29
+ }
30
+ const isInsideWorkTree = await execGit(["rev-parse", "--is-inside-work-tree"], exec);
31
+ if (!isInsideWorkTree) {
32
+ return null;
33
+ }
34
+ const [remoteUrl, commit, commitTime, branch, tags, dirty, authorName, authorEmail,] = await Promise.all([
35
+ execGit(["remote", "get-url", remote], exec),
36
+ execGit(["rev-parse", "HEAD"], exec),
37
+ execGit(["log", "-1", "--format=%ct"], exec),
38
+ execGit(["rev-parse", "--abbrev-ref", "HEAD"], exec),
39
+ execGit(["describe", "--tags", "--exact-match", "--always", "--dirty"], exec),
40
+ execGit(["status", "--porcelain"], exec).then((output) => output !== ""),
41
+ execGit(["log", "-1", "--format=%an"], exec),
42
+ execGit(["log", "-1", "--format=%ae"], exec),
43
+ ]);
44
+ return {
45
+ remoteUrl,
46
+ commit,
47
+ commitTime,
48
+ branch,
49
+ tags,
50
+ dirty,
51
+ authorName,
52
+ authorEmail,
53
+ };
54
+ };
55
+ exports.getGitInfo = getGitInfo;
56
+ const getDefaultRevisionId = async () => {
57
+ let exec;
58
+ try {
59
+ const execImport = await importChildProcess();
60
+ exec = execImport.exec;
61
+ }
62
+ catch (e) {
63
+ // no-op
64
+ return null;
65
+ }
66
+ const commit = await execGit(["rev-parse", "HEAD"], exec);
67
+ if (!commit) {
68
+ return null;
69
+ }
70
+ return commit;
71
+ };
72
+ exports.getDefaultRevisionId = getDefaultRevisionId;
@@ -0,0 +1,14 @@
1
+ interface GitInfo {
2
+ remoteUrl?: string | null;
3
+ commit?: string | null;
4
+ branch?: string | null;
5
+ authorName?: string | null;
6
+ authorEmail?: string | null;
7
+ commitMessage?: string | null;
8
+ commitTime?: string | null;
9
+ dirty?: boolean | null;
10
+ tags?: string | null;
11
+ }
12
+ export declare const getGitInfo: (remote?: string) => Promise<GitInfo | null>;
13
+ export declare const getDefaultRevisionId: () => Promise<string | null>;
14
+ export {};
@@ -0,0 +1,67 @@
1
+ async function importChildProcess() {
2
+ const { exec } = await import("child_process");
3
+ return { exec };
4
+ }
5
+ const execGit = (command, exec) => {
6
+ return new Promise((resolve) => {
7
+ exec(`git ${command.join(" ")}`, (error, stdout) => {
8
+ if (error) {
9
+ resolve(null);
10
+ }
11
+ else {
12
+ resolve(stdout.trim());
13
+ }
14
+ });
15
+ });
16
+ };
17
+ export const getGitInfo = async (remote = "origin") => {
18
+ let exec;
19
+ try {
20
+ const execImport = await importChildProcess();
21
+ exec = execImport.exec;
22
+ }
23
+ catch (e) {
24
+ // no-op
25
+ return null;
26
+ }
27
+ const isInsideWorkTree = await execGit(["rev-parse", "--is-inside-work-tree"], exec);
28
+ if (!isInsideWorkTree) {
29
+ return null;
30
+ }
31
+ const [remoteUrl, commit, commitTime, branch, tags, dirty, authorName, authorEmail,] = await Promise.all([
32
+ execGit(["remote", "get-url", remote], exec),
33
+ execGit(["rev-parse", "HEAD"], exec),
34
+ execGit(["log", "-1", "--format=%ct"], exec),
35
+ execGit(["rev-parse", "--abbrev-ref", "HEAD"], exec),
36
+ execGit(["describe", "--tags", "--exact-match", "--always", "--dirty"], exec),
37
+ execGit(["status", "--porcelain"], exec).then((output) => output !== ""),
38
+ execGit(["log", "-1", "--format=%an"], exec),
39
+ execGit(["log", "-1", "--format=%ae"], exec),
40
+ ]);
41
+ return {
42
+ remoteUrl,
43
+ commit,
44
+ commitTime,
45
+ branch,
46
+ tags,
47
+ dirty,
48
+ authorName,
49
+ authorEmail,
50
+ };
51
+ };
52
+ export const getDefaultRevisionId = async () => {
53
+ let exec;
54
+ try {
55
+ const execImport = await importChildProcess();
56
+ exec = execImport.exec;
57
+ }
58
+ catch (e) {
59
+ // no-op
60
+ return null;
61
+ }
62
+ const commit = await execGit(["rev-parse", "HEAD"], exec);
63
+ if (!commit) {
64
+ return null;
65
+ }
66
+ return commit;
67
+ };
@@ -0,0 +1,33 @@
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 __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || function (mod) {
19
+ if (mod && mod.__esModule) return mod;
20
+ var result = {};
21
+ if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
22
+ __setModuleDefault(result, mod);
23
+ return result;
24
+ };
25
+ Object.defineProperty(exports, "__esModule", { value: true });
26
+ exports.assertUuid = void 0;
27
+ const uuid = __importStar(require("uuid"));
28
+ function assertUuid(str) {
29
+ if (!uuid.validate(str)) {
30
+ throw new Error(`Invalid UUID: ${str}`);
31
+ }
32
+ }
33
+ exports.assertUuid = assertUuid;
@@ -0,0 +1 @@
1
+ export declare function assertUuid(str: string): void;
@@ -0,0 +1,6 @@
1
+ import * as uuid from "uuid";
2
+ export function assertUuid(str) {
3
+ if (!uuid.validate(str)) {
4
+ throw new Error(`Invalid UUID: ${str}`);
5
+ }
6
+ }
@@ -0,0 +1,24 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.atee = void 0;
4
+ function atee(iter, length = 2) {
5
+ const buffers = Array.from({ length }, () => []);
6
+ return buffers.map(async function* makeIter(buffer) {
7
+ while (true) {
8
+ if (buffer.length === 0) {
9
+ const result = await iter.next();
10
+ for (const buffer of buffers) {
11
+ buffer.push(result);
12
+ }
13
+ }
14
+ else if (buffer[0].done) {
15
+ return;
16
+ }
17
+ else {
18
+ // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
19
+ yield buffer.shift().value;
20
+ }
21
+ }
22
+ });
23
+ }
24
+ exports.atee = atee;
@@ -0,0 +1 @@
1
+ export declare function atee<T>(iter: AsyncGenerator<T>, length?: number): AsyncGenerator<T>[];
@@ -0,0 +1,20 @@
1
+ export function atee(iter, length = 2) {
2
+ const buffers = Array.from({ length }, () => []);
3
+ return buffers.map(async function* makeIter(buffer) {
4
+ while (true) {
5
+ if (buffer.length === 0) {
6
+ const result = await iter.next();
7
+ for (const buffer of buffers) {
8
+ buffer.push(result);
9
+ }
10
+ }
11
+ else if (buffer[0].done) {
12
+ return;
13
+ }
14
+ else {
15
+ // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
16
+ yield buffer.shift().value;
17
+ }
18
+ }
19
+ });
20
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "langsmith",
3
- "version": "0.1.21",
3
+ "version": "0.1.23-rc.0",
4
4
  "description": "Client library to connect to the LangSmith LLM Tracing and Evaluation Platform.",
5
5
  "packageManager": "yarn@1.22.19",
6
6
  "files": [
@@ -52,6 +52,7 @@
52
52
  "test": "cross-env NODE_OPTIONS=--experimental-vm-modules jest --passWithNoTests --testPathIgnorePatterns='\\.int\\.test.[tj]s' --testTimeout 30000",
53
53
  "test:integration": "cross-env NODE_OPTIONS=--experimental-vm-modules jest --testPathPattern=\\.int\\.test.ts --testTimeout 100000",
54
54
  "test:single": "NODE_OPTIONS=--experimental-vm-modules yarn run jest --config jest.config.cjs --testTimeout 100000",
55
+ "watch:single": "NODE_OPTIONS=--experimental-vm-modules yarn run jest --watch --config jest.config.cjs --testTimeout 100000",
55
56
  "lint": "NODE_OPTIONS=--max-old-space-size=4096 eslint --cache --ext .ts,.js src/",
56
57
  "lint:fix": "yarn lint --fix",
57
58
  "format": "prettier --write 'src/**/*.{ts,tsx}'",