braintrust 0.0.142 → 0.0.143

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.
@@ -201,7 +201,7 @@ declare class BraintrustState {
201
201
  resetLoginInfo(): void;
202
202
  copyLoginInfo(other: BraintrustState): void;
203
203
  serialize(): SerializedBraintrustState;
204
- static deserialize(serialized: unknown): BraintrustState;
204
+ static deserialize(serialized: unknown, opts?: BackgroundLoggerOpts): BraintrustState;
205
205
  setFetch(fetch: typeof globalThis.fetch): void;
206
206
  login(loginParams: LoginOptions & {
207
207
  forceLogin?: boolean;
@@ -323,6 +323,9 @@ declare class Logger<IsAsyncFlush extends boolean> implements Exportable {
323
323
  flush(): Promise<void>;
324
324
  get asyncFlush(): IsAsyncFlush | undefined;
325
325
  }
326
+ interface BackgroundLoggerOpts {
327
+ noExitFlush?: boolean;
328
+ }
326
329
  declare class BackgroundLogger {
327
330
  private apiConn;
328
331
  private items;
@@ -338,7 +341,7 @@ declare class BackgroundLogger {
338
341
  failedPublishPayloadsDir: string | undefined;
339
342
  allPublishPayloadsDir: string | undefined;
340
343
  private queueDropLoggingState;
341
- constructor(apiConn: LazyValue<HTTPConnection>);
344
+ constructor(apiConn: LazyValue<HTTPConnection>, opts?: BackgroundLoggerOpts);
342
345
  log(items: LazyValue<BackgroundLogEvent>[]): void;
343
346
  flush(): Promise<void>;
344
347
  private flushOnce;
@@ -539,6 +542,11 @@ interface LoginOptions {
539
542
  * A custom fetch implementation to use.
540
543
  */
541
544
  fetch?: typeof globalThis.fetch;
545
+ /**
546
+ * By default, the SDK installs an event handler that flushes pending writes on the `beforeExit` event.
547
+ * If true, this event handler will _not_ be installed.
548
+ */
549
+ noExitFlush?: boolean;
542
550
  }
543
551
  type FullLoginOptions = LoginOptions & {
544
552
  forceLogin?: boolean;
@@ -608,7 +616,7 @@ declare function getSpanParentObject<IsAsyncFlush extends boolean>(options?: Asy
608
616
  *
609
617
  * See `Span.traced` for full details.
610
618
  */
611
- declare function traced<IsAsyncFlush extends boolean = false, R = void>(callback: (span: Span) => R, args?: StartSpanArgs & SetCurrentArg & AsyncFlushArg<IsAsyncFlush>): PromiseUnless<IsAsyncFlush, R>;
619
+ declare function traced<IsAsyncFlush extends boolean = false, R = void>(callback: (span: Span) => R, args?: StartSpanArgs & SetCurrentArg & AsyncFlushArg<IsAsyncFlush> & OptionalStateArg): PromiseUnless<IsAsyncFlush, R>;
612
620
  /**
613
621
  * Wrap a function with `traced`, using the arguments as `input` and return value as `output`.
614
622
  * Any functions wrapped this way will automatically be traced, similar to the `@traced` decorator
@@ -1207,4 +1215,4 @@ declare const LEGACY_CACHED_HEADER = "x-cached";
1207
1215
  declare const X_CACHED_HEADER = "x-bt-cached";
1208
1216
  declare function parseCachedHeader(value: string | null | undefined): number | undefined;
1209
1217
 
1210
- export { type AnyDataset, type BaseMetadata, BraintrustState, BraintrustStream, type BraintrustStreamChunk, type ChatPrompt, type CompiledPrompt, type CompiledPromptParams, type CompletionPrompt, type DataSummary, Dataset, type DatasetSummary, type DefaultMetadataType, type DefaultPromptArgs, type EndSpanArgs, type EvalCase, Experiment, type ExperimentSummary, type Exportable, type FullInitOptions, type FullLoginOptions, type InitOptions, type InvokeFunctionArgs, type InvokeReturn, LEGACY_CACHED_HEADER, type LogOptions, Logger, type LoginOptions, type MetricSummary, NOOP_SPAN, NoopSpan, type ObjectMetadata, type PromiseUnless, Prompt, ReadonlyExperiment, type ScoreSummary, type SerializedBraintrustState, type SetCurrentArg, type Span, SpanImpl, type StartSpanArgs, type WithTransactionId, X_CACHED_HEADER, _internalGetGlobalState, _internalSetInitialState, braintrustStreamChunkSchema, createFinalValuePassThroughStream, currentExperiment, currentLogger, currentSpan, devNullWritableStream, flush, getSpanParentObject, init, initDataset, initExperiment, initLogger, invoke, loadPrompt, log, login, loginToState, newId, parseCachedHeader, setFetch, startSpan, summarize, traceable, traced, withDataset, withExperiment, withLogger, wrapOpenAI, wrapOpenAIv4, wrapTraced };
1218
+ export { type AnyDataset, type BackgroundLoggerOpts, type BaseMetadata, BraintrustState, BraintrustStream, type BraintrustStreamChunk, type ChatPrompt, type CompiledPrompt, type CompiledPromptParams, type CompletionPrompt, type DataSummary, Dataset, type DatasetSummary, type DefaultMetadataType, type DefaultPromptArgs, type EndSpanArgs, type EvalCase, Experiment, type ExperimentSummary, type Exportable, type FullInitOptions, type FullLoginOptions, type InitOptions, type InvokeFunctionArgs, type InvokeReturn, LEGACY_CACHED_HEADER, type LogOptions, Logger, type LoginOptions, type MetricSummary, NOOP_SPAN, NoopSpan, type ObjectMetadata, type PromiseUnless, Prompt, ReadonlyExperiment, type ScoreSummary, type SerializedBraintrustState, type SetCurrentArg, type Span, SpanImpl, type StartSpanArgs, type WithTransactionId, X_CACHED_HEADER, _internalGetGlobalState, _internalSetInitialState, braintrustStreamChunkSchema, createFinalValuePassThroughStream, currentExperiment, currentLogger, currentSpan, devNullWritableStream, flush, getSpanParentObject, init, initDataset, initExperiment, initLogger, invoke, loadPrompt, log, login, loginToState, newId, parseCachedHeader, setFetch, startSpan, summarize, traceable, traced, withDataset, withExperiment, withLogger, wrapOpenAI, wrapOpenAIv4, wrapTraced };
package/dist/browser.d.ts CHANGED
@@ -201,7 +201,7 @@ declare class BraintrustState {
201
201
  resetLoginInfo(): void;
202
202
  copyLoginInfo(other: BraintrustState): void;
203
203
  serialize(): SerializedBraintrustState;
204
- static deserialize(serialized: unknown): BraintrustState;
204
+ static deserialize(serialized: unknown, opts?: BackgroundLoggerOpts): BraintrustState;
205
205
  setFetch(fetch: typeof globalThis.fetch): void;
206
206
  login(loginParams: LoginOptions & {
207
207
  forceLogin?: boolean;
@@ -323,6 +323,9 @@ declare class Logger<IsAsyncFlush extends boolean> implements Exportable {
323
323
  flush(): Promise<void>;
324
324
  get asyncFlush(): IsAsyncFlush | undefined;
325
325
  }
326
+ interface BackgroundLoggerOpts {
327
+ noExitFlush?: boolean;
328
+ }
326
329
  declare class BackgroundLogger {
327
330
  private apiConn;
328
331
  private items;
@@ -338,7 +341,7 @@ declare class BackgroundLogger {
338
341
  failedPublishPayloadsDir: string | undefined;
339
342
  allPublishPayloadsDir: string | undefined;
340
343
  private queueDropLoggingState;
341
- constructor(apiConn: LazyValue<HTTPConnection>);
344
+ constructor(apiConn: LazyValue<HTTPConnection>, opts?: BackgroundLoggerOpts);
342
345
  log(items: LazyValue<BackgroundLogEvent>[]): void;
343
346
  flush(): Promise<void>;
344
347
  private flushOnce;
@@ -539,6 +542,11 @@ interface LoginOptions {
539
542
  * A custom fetch implementation to use.
540
543
  */
541
544
  fetch?: typeof globalThis.fetch;
545
+ /**
546
+ * By default, the SDK installs an event handler that flushes pending writes on the `beforeExit` event.
547
+ * If true, this event handler will _not_ be installed.
548
+ */
549
+ noExitFlush?: boolean;
542
550
  }
543
551
  type FullLoginOptions = LoginOptions & {
544
552
  forceLogin?: boolean;
@@ -608,7 +616,7 @@ declare function getSpanParentObject<IsAsyncFlush extends boolean>(options?: Asy
608
616
  *
609
617
  * See `Span.traced` for full details.
610
618
  */
611
- declare function traced<IsAsyncFlush extends boolean = false, R = void>(callback: (span: Span) => R, args?: StartSpanArgs & SetCurrentArg & AsyncFlushArg<IsAsyncFlush>): PromiseUnless<IsAsyncFlush, R>;
619
+ declare function traced<IsAsyncFlush extends boolean = false, R = void>(callback: (span: Span) => R, args?: StartSpanArgs & SetCurrentArg & AsyncFlushArg<IsAsyncFlush> & OptionalStateArg): PromiseUnless<IsAsyncFlush, R>;
612
620
  /**
613
621
  * Wrap a function with `traced`, using the arguments as `input` and return value as `output`.
614
622
  * Any functions wrapped this way will automatically be traced, similar to the `@traced` decorator
@@ -1207,4 +1215,4 @@ declare const LEGACY_CACHED_HEADER = "x-cached";
1207
1215
  declare const X_CACHED_HEADER = "x-bt-cached";
1208
1216
  declare function parseCachedHeader(value: string | null | undefined): number | undefined;
1209
1217
 
1210
- export { type AnyDataset, type BaseMetadata, BraintrustState, BraintrustStream, type BraintrustStreamChunk, type ChatPrompt, type CompiledPrompt, type CompiledPromptParams, type CompletionPrompt, type DataSummary, Dataset, type DatasetSummary, type DefaultMetadataType, type DefaultPromptArgs, type EndSpanArgs, type EvalCase, Experiment, type ExperimentSummary, type Exportable, type FullInitOptions, type FullLoginOptions, type InitOptions, type InvokeFunctionArgs, type InvokeReturn, LEGACY_CACHED_HEADER, type LogOptions, Logger, type LoginOptions, type MetricSummary, NOOP_SPAN, NoopSpan, type ObjectMetadata, type PromiseUnless, Prompt, ReadonlyExperiment, type ScoreSummary, type SerializedBraintrustState, type SetCurrentArg, type Span, SpanImpl, type StartSpanArgs, type WithTransactionId, X_CACHED_HEADER, _internalGetGlobalState, _internalSetInitialState, braintrustStreamChunkSchema, createFinalValuePassThroughStream, currentExperiment, currentLogger, currentSpan, devNullWritableStream, flush, getSpanParentObject, init, initDataset, initExperiment, initLogger, invoke, loadPrompt, log, login, loginToState, newId, parseCachedHeader, setFetch, startSpan, summarize, traceable, traced, withDataset, withExperiment, withLogger, wrapOpenAI, wrapOpenAIv4, wrapTraced };
1218
+ export { type AnyDataset, type BackgroundLoggerOpts, type BaseMetadata, BraintrustState, BraintrustStream, type BraintrustStreamChunk, type ChatPrompt, type CompiledPrompt, type CompiledPromptParams, type CompletionPrompt, type DataSummary, Dataset, type DatasetSummary, type DefaultMetadataType, type DefaultPromptArgs, type EndSpanArgs, type EvalCase, Experiment, type ExperimentSummary, type Exportable, type FullInitOptions, type FullLoginOptions, type InitOptions, type InvokeFunctionArgs, type InvokeReturn, LEGACY_CACHED_HEADER, type LogOptions, Logger, type LoginOptions, type MetricSummary, NOOP_SPAN, NoopSpan, type ObjectMetadata, type PromiseUnless, Prompt, ReadonlyExperiment, type ScoreSummary, type SerializedBraintrustState, type SetCurrentArg, type Span, SpanImpl, type StartSpanArgs, type WithTransactionId, X_CACHED_HEADER, _internalGetGlobalState, _internalSetInitialState, braintrustStreamChunkSchema, createFinalValuePassThroughStream, currentExperiment, currentLogger, currentSpan, devNullWritableStream, flush, getSpanParentObject, init, initDataset, initExperiment, initLogger, invoke, loadPrompt, log, login, loginToState, newId, parseCachedHeader, setFetch, startSpan, summarize, traceable, traced, withDataset, withExperiment, withLogger, wrapOpenAI, wrapOpenAIv4, wrapTraced };
package/dist/browser.js CHANGED
@@ -373,10 +373,11 @@ var loginSchema = import_zod2.z.strictObject({
373
373
  orgId: import_zod2.z.string().nullish(),
374
374
  gitMetadataSettings: import_core.gitMetadataSettingsSchema.nullish()
375
375
  });
376
+ var stateNonce = 0;
376
377
  var BraintrustState = class _BraintrustState {
377
378
  constructor(loginParams) {
378
379
  this.loginParams = loginParams;
379
- this.id = (/* @__PURE__ */ new Date()).toLocaleString();
380
+ this.id = `${(/* @__PURE__ */ new Date()).toLocaleString()}-${stateNonce++}`;
380
381
  this.currentExperiment = void 0;
381
382
  this.currentLogger = void 0;
382
383
  this.currentSpan = isomorph_default.newAsyncLocalStorage();
@@ -387,7 +388,10 @@ var BraintrustState = class _BraintrustState {
387
388
  await this.login({});
388
389
  return this.apiConn();
389
390
  };
390
- this._bgLogger = new BackgroundLogger(new LazyValue(defaultGetLogConn));
391
+ this._bgLogger = new BackgroundLogger(
392
+ new LazyValue(defaultGetLogConn),
393
+ loginParams
394
+ );
391
395
  this.resetLoginInfo();
392
396
  }
393
397
  id;
@@ -464,14 +468,14 @@ var BraintrustState = class _BraintrustState {
464
468
  gitMetadataSettings: this.gitMetadataSettings
465
469
  };
466
470
  }
467
- static deserialize(serialized) {
471
+ static deserialize(serialized, opts) {
468
472
  const serializedParsed = loginSchema.safeParse(serialized);
469
473
  if (!serializedParsed.success) {
470
474
  throw new Error(
471
475
  `Cannot deserialize BraintrustState: ${serializedParsed.error.errors}`
472
476
  );
473
477
  }
474
- const state = new _BraintrustState({});
478
+ const state = new _BraintrustState({ ...opts });
475
479
  for (const key of Object.keys(loginSchema.shape)) {
476
480
  state[key] = serializedParsed.data[key];
477
481
  }
@@ -1007,7 +1011,8 @@ var BackgroundLogger = class _BackgroundLogger {
1007
1011
  numDropped: 0,
1008
1012
  lastLoggedTimestamp: 0
1009
1013
  };
1010
- constructor(apiConn) {
1014
+ constructor(apiConn, opts) {
1015
+ opts = opts ?? {};
1011
1016
  this.apiConn = apiConn;
1012
1017
  const syncFlushEnv = Number(isomorph_default.getEnv("BRAINTRUST_SYNC_FLUSH"));
1013
1018
  if (!isNaN(syncFlushEnv)) {
@@ -1051,9 +1056,11 @@ var BackgroundLogger = class _BackgroundLogger {
1051
1056
  if (allPublishPayloadsDirEnv) {
1052
1057
  this.allPublishPayloadsDir = allPublishPayloadsDirEnv;
1053
1058
  }
1054
- isomorph_default.processOn("beforeExit", async () => {
1055
- await this.flush();
1056
- });
1059
+ if (!opts.noExitFlush) {
1060
+ isomorph_default.processOn("beforeExit", async () => {
1061
+ await this.flush();
1062
+ });
1063
+ }
1057
1064
  }
1058
1065
  log(items) {
1059
1066
  const [addedItems, droppedItems] = (() => {
package/dist/browser.mjs CHANGED
@@ -319,10 +319,11 @@ var loginSchema = z2.strictObject({
319
319
  orgId: z2.string().nullish(),
320
320
  gitMetadataSettings: gitMetadataSettingsSchema.nullish()
321
321
  });
322
+ var stateNonce = 0;
322
323
  var BraintrustState = class _BraintrustState {
323
324
  constructor(loginParams) {
324
325
  this.loginParams = loginParams;
325
- this.id = (/* @__PURE__ */ new Date()).toLocaleString();
326
+ this.id = `${(/* @__PURE__ */ new Date()).toLocaleString()}-${stateNonce++}`;
326
327
  this.currentExperiment = void 0;
327
328
  this.currentLogger = void 0;
328
329
  this.currentSpan = isomorph_default.newAsyncLocalStorage();
@@ -333,7 +334,10 @@ var BraintrustState = class _BraintrustState {
333
334
  await this.login({});
334
335
  return this.apiConn();
335
336
  };
336
- this._bgLogger = new BackgroundLogger(new LazyValue(defaultGetLogConn));
337
+ this._bgLogger = new BackgroundLogger(
338
+ new LazyValue(defaultGetLogConn),
339
+ loginParams
340
+ );
337
341
  this.resetLoginInfo();
338
342
  }
339
343
  id;
@@ -410,14 +414,14 @@ var BraintrustState = class _BraintrustState {
410
414
  gitMetadataSettings: this.gitMetadataSettings
411
415
  };
412
416
  }
413
- static deserialize(serialized) {
417
+ static deserialize(serialized, opts) {
414
418
  const serializedParsed = loginSchema.safeParse(serialized);
415
419
  if (!serializedParsed.success) {
416
420
  throw new Error(
417
421
  `Cannot deserialize BraintrustState: ${serializedParsed.error.errors}`
418
422
  );
419
423
  }
420
- const state = new _BraintrustState({});
424
+ const state = new _BraintrustState({ ...opts });
421
425
  for (const key of Object.keys(loginSchema.shape)) {
422
426
  state[key] = serializedParsed.data[key];
423
427
  }
@@ -953,7 +957,8 @@ var BackgroundLogger = class _BackgroundLogger {
953
957
  numDropped: 0,
954
958
  lastLoggedTimestamp: 0
955
959
  };
956
- constructor(apiConn) {
960
+ constructor(apiConn, opts) {
961
+ opts = opts ?? {};
957
962
  this.apiConn = apiConn;
958
963
  const syncFlushEnv = Number(isomorph_default.getEnv("BRAINTRUST_SYNC_FLUSH"));
959
964
  if (!isNaN(syncFlushEnv)) {
@@ -997,9 +1002,11 @@ var BackgroundLogger = class _BackgroundLogger {
997
1002
  if (allPublishPayloadsDirEnv) {
998
1003
  this.allPublishPayloadsDir = allPublishPayloadsDirEnv;
999
1004
  }
1000
- isomorph_default.processOn("beforeExit", async () => {
1001
- await this.flush();
1002
- });
1005
+ if (!opts.noExitFlush) {
1006
+ isomorph_default.processOn("beforeExit", async () => {
1007
+ await this.flush();
1008
+ });
1009
+ }
1003
1010
  }
1004
1011
  log(items) {
1005
1012
  const [addedItems, droppedItems] = (() => {
package/dist/cli.js CHANGED
@@ -1232,7 +1232,7 @@ var require_package = __commonJS({
1232
1232
  "package.json"(exports2, module2) {
1233
1233
  module2.exports = {
1234
1234
  name: "braintrust",
1235
- version: "0.0.142",
1235
+ version: "0.0.143",
1236
1236
  description: "SDK for integrating Braintrust",
1237
1237
  main: "./dist/index.js",
1238
1238
  module: "./dist/index.mjs",
@@ -1632,10 +1632,11 @@ var loginSchema = import_zod2.z.strictObject({
1632
1632
  orgId: import_zod2.z.string().nullish(),
1633
1633
  gitMetadataSettings: import_core.gitMetadataSettingsSchema.nullish()
1634
1634
  });
1635
+ var stateNonce = 0;
1635
1636
  var BraintrustState = class _BraintrustState {
1636
1637
  constructor(loginParams) {
1637
1638
  this.loginParams = loginParams;
1638
- this.id = (/* @__PURE__ */ new Date()).toLocaleString();
1639
+ this.id = `${(/* @__PURE__ */ new Date()).toLocaleString()}-${stateNonce++}`;
1639
1640
  this.currentExperiment = void 0;
1640
1641
  this.currentLogger = void 0;
1641
1642
  this.currentSpan = isomorph_default.newAsyncLocalStorage();
@@ -1646,7 +1647,10 @@ var BraintrustState = class _BraintrustState {
1646
1647
  await this.login({});
1647
1648
  return this.apiConn();
1648
1649
  };
1649
- this._bgLogger = new BackgroundLogger(new LazyValue(defaultGetLogConn));
1650
+ this._bgLogger = new BackgroundLogger(
1651
+ new LazyValue(defaultGetLogConn),
1652
+ loginParams
1653
+ );
1650
1654
  this.resetLoginInfo();
1651
1655
  }
1652
1656
  id;
@@ -1723,14 +1727,14 @@ var BraintrustState = class _BraintrustState {
1723
1727
  gitMetadataSettings: this.gitMetadataSettings
1724
1728
  };
1725
1729
  }
1726
- static deserialize(serialized) {
1730
+ static deserialize(serialized, opts) {
1727
1731
  const serializedParsed = loginSchema.safeParse(serialized);
1728
1732
  if (!serializedParsed.success) {
1729
1733
  throw new Error(
1730
1734
  `Cannot deserialize BraintrustState: ${serializedParsed.error.errors}`
1731
1735
  );
1732
1736
  }
1733
- const state = new _BraintrustState({});
1737
+ const state = new _BraintrustState({ ...opts });
1734
1738
  for (const key of Object.keys(loginSchema.shape)) {
1735
1739
  state[key] = serializedParsed.data[key];
1736
1740
  }
@@ -2256,7 +2260,8 @@ var BackgroundLogger = class _BackgroundLogger {
2256
2260
  numDropped: 0,
2257
2261
  lastLoggedTimestamp: 0
2258
2262
  };
2259
- constructor(apiConn) {
2263
+ constructor(apiConn, opts) {
2264
+ opts = opts ?? {};
2260
2265
  this.apiConn = apiConn;
2261
2266
  const syncFlushEnv = Number(isomorph_default.getEnv("BRAINTRUST_SYNC_FLUSH"));
2262
2267
  if (!isNaN(syncFlushEnv)) {
@@ -2300,9 +2305,11 @@ var BackgroundLogger = class _BackgroundLogger {
2300
2305
  if (allPublishPayloadsDirEnv) {
2301
2306
  this.allPublishPayloadsDir = allPublishPayloadsDirEnv;
2302
2307
  }
2303
- isomorph_default.processOn("beforeExit", async () => {
2304
- await this.flush();
2305
- });
2308
+ if (!opts.noExitFlush) {
2309
+ isomorph_default.processOn("beforeExit", async () => {
2310
+ await this.flush();
2311
+ });
2312
+ }
2306
2313
  }
2307
2314
  log(items) {
2308
2315
  const [addedItems, droppedItems] = (() => {
package/dist/index.d.mts CHANGED
@@ -202,7 +202,7 @@ declare class BraintrustState {
202
202
  resetLoginInfo(): void;
203
203
  copyLoginInfo(other: BraintrustState): void;
204
204
  serialize(): SerializedBraintrustState;
205
- static deserialize(serialized: unknown): BraintrustState;
205
+ static deserialize(serialized: unknown, opts?: BackgroundLoggerOpts): BraintrustState;
206
206
  setFetch(fetch: typeof globalThis.fetch): void;
207
207
  login(loginParams: LoginOptions & {
208
208
  forceLogin?: boolean;
@@ -324,6 +324,9 @@ declare class Logger<IsAsyncFlush extends boolean> implements Exportable {
324
324
  flush(): Promise<void>;
325
325
  get asyncFlush(): IsAsyncFlush | undefined;
326
326
  }
327
+ interface BackgroundLoggerOpts {
328
+ noExitFlush?: boolean;
329
+ }
327
330
  declare class BackgroundLogger {
328
331
  private apiConn;
329
332
  private items;
@@ -339,7 +342,7 @@ declare class BackgroundLogger {
339
342
  failedPublishPayloadsDir: string | undefined;
340
343
  allPublishPayloadsDir: string | undefined;
341
344
  private queueDropLoggingState;
342
- constructor(apiConn: LazyValue<HTTPConnection>);
345
+ constructor(apiConn: LazyValue<HTTPConnection>, opts?: BackgroundLoggerOpts);
343
346
  log(items: LazyValue<BackgroundLogEvent>[]): void;
344
347
  flush(): Promise<void>;
345
348
  private flushOnce;
@@ -540,6 +543,11 @@ interface LoginOptions {
540
543
  * A custom fetch implementation to use.
541
544
  */
542
545
  fetch?: typeof globalThis.fetch;
546
+ /**
547
+ * By default, the SDK installs an event handler that flushes pending writes on the `beforeExit` event.
548
+ * If true, this event handler will _not_ be installed.
549
+ */
550
+ noExitFlush?: boolean;
543
551
  }
544
552
  type FullLoginOptions = LoginOptions & {
545
553
  forceLogin?: boolean;
@@ -609,7 +617,7 @@ declare function getSpanParentObject<IsAsyncFlush extends boolean>(options?: Asy
609
617
  *
610
618
  * See `Span.traced` for full details.
611
619
  */
612
- declare function traced<IsAsyncFlush extends boolean = false, R = void>(callback: (span: Span) => R, args?: StartSpanArgs & SetCurrentArg & AsyncFlushArg<IsAsyncFlush>): PromiseUnless<IsAsyncFlush, R>;
620
+ declare function traced<IsAsyncFlush extends boolean = false, R = void>(callback: (span: Span) => R, args?: StartSpanArgs & SetCurrentArg & AsyncFlushArg<IsAsyncFlush> & OptionalStateArg): PromiseUnless<IsAsyncFlush, R>;
613
621
  /**
614
622
  * Wrap a function with `traced`, using the arguments as `input` and return value as `output`.
615
623
  * Any functions wrapped this way will automatically be traced, similar to the `@traced` decorator
@@ -1368,4 +1376,4 @@ declare function parseCachedHeader(value: string | null | undefined): number | u
1368
1376
  */
1369
1377
  declare function wrapAISDKModel<T extends object>(model: T): T;
1370
1378
 
1371
- export { type AnyDataset, BaseExperiment, type BaseMetadata, BraintrustState, BraintrustStream, type BraintrustStreamChunk, type ChatPrompt, type CompiledPrompt, type CompiledPromptParams, type CompletionPrompt, type DataSummary, Dataset, type DatasetSummary, type DefaultMetadataType, type DefaultPromptArgs, type EndSpanArgs, Eval, type EvalCase, type EvalScorerArgs, type EvalTask, type Evaluator, Experiment, type ExperimentSummary, type Exportable, type FullInitOptions, type FullLoginOptions, type InitOptions, type InvokeFunctionArgs, type InvokeReturn, LEGACY_CACHED_HEADER, LazyValue, type LogOptions, Logger, type LoginOptions, type MetricSummary, NOOP_SPAN, NoopSpan, type ObjectMetadata, type PromiseUnless, Prompt, ReadonlyExperiment, Reporter, type ReporterBody, type ScoreSummary, type SerializedBraintrustState, type SetCurrentArg, type Span, SpanImpl, type StartSpanArgs, type WithTransactionId, X_CACHED_HEADER, _internalGetGlobalState, _internalSetInitialState, braintrustStreamChunkSchema, buildLocalSummary, createFinalValuePassThroughStream, currentExperiment, currentLogger, currentSpan, devNullWritableStream, flush, getSpanParentObject, init, initDataset, initExperiment, initLogger, invoke, loadPrompt, log, login, loginToState, newId, parseCachedHeader, reportFailures, setFetch, startSpan, summarize, traceable, traced, withDataset, withExperiment, withLogger, wrapAISDKModel, wrapOpenAI, wrapOpenAIv4, wrapTraced };
1379
+ export { type AnyDataset, type BackgroundLoggerOpts, BaseExperiment, type BaseMetadata, BraintrustState, BraintrustStream, type BraintrustStreamChunk, type ChatPrompt, type CompiledPrompt, type CompiledPromptParams, type CompletionPrompt, type DataSummary, Dataset, type DatasetSummary, type DefaultMetadataType, type DefaultPromptArgs, type EndSpanArgs, Eval, type EvalCase, type EvalScorerArgs, type EvalTask, type Evaluator, Experiment, type ExperimentSummary, type Exportable, type FullInitOptions, type FullLoginOptions, type InitOptions, type InvokeFunctionArgs, type InvokeReturn, LEGACY_CACHED_HEADER, LazyValue, type LogOptions, Logger, type LoginOptions, type MetricSummary, NOOP_SPAN, NoopSpan, type ObjectMetadata, type PromiseUnless, Prompt, ReadonlyExperiment, Reporter, type ReporterBody, type ScoreSummary, type SerializedBraintrustState, type SetCurrentArg, type Span, SpanImpl, type StartSpanArgs, type WithTransactionId, X_CACHED_HEADER, _internalGetGlobalState, _internalSetInitialState, braintrustStreamChunkSchema, buildLocalSummary, createFinalValuePassThroughStream, currentExperiment, currentLogger, currentSpan, devNullWritableStream, flush, getSpanParentObject, init, initDataset, initExperiment, initLogger, invoke, loadPrompt, log, login, loginToState, newId, parseCachedHeader, reportFailures, setFetch, startSpan, summarize, traceable, traced, withDataset, withExperiment, withLogger, wrapAISDKModel, wrapOpenAI, wrapOpenAIv4, wrapTraced };
package/dist/index.d.ts CHANGED
@@ -202,7 +202,7 @@ declare class BraintrustState {
202
202
  resetLoginInfo(): void;
203
203
  copyLoginInfo(other: BraintrustState): void;
204
204
  serialize(): SerializedBraintrustState;
205
- static deserialize(serialized: unknown): BraintrustState;
205
+ static deserialize(serialized: unknown, opts?: BackgroundLoggerOpts): BraintrustState;
206
206
  setFetch(fetch: typeof globalThis.fetch): void;
207
207
  login(loginParams: LoginOptions & {
208
208
  forceLogin?: boolean;
@@ -324,6 +324,9 @@ declare class Logger<IsAsyncFlush extends boolean> implements Exportable {
324
324
  flush(): Promise<void>;
325
325
  get asyncFlush(): IsAsyncFlush | undefined;
326
326
  }
327
+ interface BackgroundLoggerOpts {
328
+ noExitFlush?: boolean;
329
+ }
327
330
  declare class BackgroundLogger {
328
331
  private apiConn;
329
332
  private items;
@@ -339,7 +342,7 @@ declare class BackgroundLogger {
339
342
  failedPublishPayloadsDir: string | undefined;
340
343
  allPublishPayloadsDir: string | undefined;
341
344
  private queueDropLoggingState;
342
- constructor(apiConn: LazyValue<HTTPConnection>);
345
+ constructor(apiConn: LazyValue<HTTPConnection>, opts?: BackgroundLoggerOpts);
343
346
  log(items: LazyValue<BackgroundLogEvent>[]): void;
344
347
  flush(): Promise<void>;
345
348
  private flushOnce;
@@ -540,6 +543,11 @@ interface LoginOptions {
540
543
  * A custom fetch implementation to use.
541
544
  */
542
545
  fetch?: typeof globalThis.fetch;
546
+ /**
547
+ * By default, the SDK installs an event handler that flushes pending writes on the `beforeExit` event.
548
+ * If true, this event handler will _not_ be installed.
549
+ */
550
+ noExitFlush?: boolean;
543
551
  }
544
552
  type FullLoginOptions = LoginOptions & {
545
553
  forceLogin?: boolean;
@@ -609,7 +617,7 @@ declare function getSpanParentObject<IsAsyncFlush extends boolean>(options?: Asy
609
617
  *
610
618
  * See `Span.traced` for full details.
611
619
  */
612
- declare function traced<IsAsyncFlush extends boolean = false, R = void>(callback: (span: Span) => R, args?: StartSpanArgs & SetCurrentArg & AsyncFlushArg<IsAsyncFlush>): PromiseUnless<IsAsyncFlush, R>;
620
+ declare function traced<IsAsyncFlush extends boolean = false, R = void>(callback: (span: Span) => R, args?: StartSpanArgs & SetCurrentArg & AsyncFlushArg<IsAsyncFlush> & OptionalStateArg): PromiseUnless<IsAsyncFlush, R>;
613
621
  /**
614
622
  * Wrap a function with `traced`, using the arguments as `input` and return value as `output`.
615
623
  * Any functions wrapped this way will automatically be traced, similar to the `@traced` decorator
@@ -1368,4 +1376,4 @@ declare function parseCachedHeader(value: string | null | undefined): number | u
1368
1376
  */
1369
1377
  declare function wrapAISDKModel<T extends object>(model: T): T;
1370
1378
 
1371
- export { type AnyDataset, BaseExperiment, type BaseMetadata, BraintrustState, BraintrustStream, type BraintrustStreamChunk, type ChatPrompt, type CompiledPrompt, type CompiledPromptParams, type CompletionPrompt, type DataSummary, Dataset, type DatasetSummary, type DefaultMetadataType, type DefaultPromptArgs, type EndSpanArgs, Eval, type EvalCase, type EvalScorerArgs, type EvalTask, type Evaluator, Experiment, type ExperimentSummary, type Exportable, type FullInitOptions, type FullLoginOptions, type InitOptions, type InvokeFunctionArgs, type InvokeReturn, LEGACY_CACHED_HEADER, LazyValue, type LogOptions, Logger, type LoginOptions, type MetricSummary, NOOP_SPAN, NoopSpan, type ObjectMetadata, type PromiseUnless, Prompt, ReadonlyExperiment, Reporter, type ReporterBody, type ScoreSummary, type SerializedBraintrustState, type SetCurrentArg, type Span, SpanImpl, type StartSpanArgs, type WithTransactionId, X_CACHED_HEADER, _internalGetGlobalState, _internalSetInitialState, braintrustStreamChunkSchema, buildLocalSummary, createFinalValuePassThroughStream, currentExperiment, currentLogger, currentSpan, devNullWritableStream, flush, getSpanParentObject, init, initDataset, initExperiment, initLogger, invoke, loadPrompt, log, login, loginToState, newId, parseCachedHeader, reportFailures, setFetch, startSpan, summarize, traceable, traced, withDataset, withExperiment, withLogger, wrapAISDKModel, wrapOpenAI, wrapOpenAIv4, wrapTraced };
1379
+ export { type AnyDataset, type BackgroundLoggerOpts, BaseExperiment, type BaseMetadata, BraintrustState, BraintrustStream, type BraintrustStreamChunk, type ChatPrompt, type CompiledPrompt, type CompiledPromptParams, type CompletionPrompt, type DataSummary, Dataset, type DatasetSummary, type DefaultMetadataType, type DefaultPromptArgs, type EndSpanArgs, Eval, type EvalCase, type EvalScorerArgs, type EvalTask, type Evaluator, Experiment, type ExperimentSummary, type Exportable, type FullInitOptions, type FullLoginOptions, type InitOptions, type InvokeFunctionArgs, type InvokeReturn, LEGACY_CACHED_HEADER, LazyValue, type LogOptions, Logger, type LoginOptions, type MetricSummary, NOOP_SPAN, NoopSpan, type ObjectMetadata, type PromiseUnless, Prompt, ReadonlyExperiment, Reporter, type ReporterBody, type ScoreSummary, type SerializedBraintrustState, type SetCurrentArg, type Span, SpanImpl, type StartSpanArgs, type WithTransactionId, X_CACHED_HEADER, _internalGetGlobalState, _internalSetInitialState, braintrustStreamChunkSchema, buildLocalSummary, createFinalValuePassThroughStream, currentExperiment, currentLogger, currentSpan, devNullWritableStream, flush, getSpanParentObject, init, initDataset, initExperiment, initLogger, invoke, loadPrompt, log, login, loginToState, newId, parseCachedHeader, reportFailures, setFetch, startSpan, summarize, traceable, traced, withDataset, withExperiment, withLogger, wrapAISDKModel, wrapOpenAI, wrapOpenAIv4, wrapTraced };
package/dist/index.js CHANGED
@@ -599,10 +599,11 @@ var loginSchema = import_zod2.z.strictObject({
599
599
  orgId: import_zod2.z.string().nullish(),
600
600
  gitMetadataSettings: import_core.gitMetadataSettingsSchema.nullish()
601
601
  });
602
+ var stateNonce = 0;
602
603
  var BraintrustState = class _BraintrustState {
603
604
  constructor(loginParams) {
604
605
  this.loginParams = loginParams;
605
- this.id = (/* @__PURE__ */ new Date()).toLocaleString();
606
+ this.id = `${(/* @__PURE__ */ new Date()).toLocaleString()}-${stateNonce++}`;
606
607
  this.currentExperiment = void 0;
607
608
  this.currentLogger = void 0;
608
609
  this.currentSpan = isomorph_default.newAsyncLocalStorage();
@@ -613,7 +614,10 @@ var BraintrustState = class _BraintrustState {
613
614
  await this.login({});
614
615
  return this.apiConn();
615
616
  };
616
- this._bgLogger = new BackgroundLogger(new LazyValue(defaultGetLogConn));
617
+ this._bgLogger = new BackgroundLogger(
618
+ new LazyValue(defaultGetLogConn),
619
+ loginParams
620
+ );
617
621
  this.resetLoginInfo();
618
622
  }
619
623
  id;
@@ -690,14 +694,14 @@ var BraintrustState = class _BraintrustState {
690
694
  gitMetadataSettings: this.gitMetadataSettings
691
695
  };
692
696
  }
693
- static deserialize(serialized) {
697
+ static deserialize(serialized, opts) {
694
698
  const serializedParsed = loginSchema.safeParse(serialized);
695
699
  if (!serializedParsed.success) {
696
700
  throw new Error(
697
701
  `Cannot deserialize BraintrustState: ${serializedParsed.error.errors}`
698
702
  );
699
703
  }
700
- const state = new _BraintrustState({});
704
+ const state = new _BraintrustState({ ...opts });
701
705
  for (const key of Object.keys(loginSchema.shape)) {
702
706
  state[key] = serializedParsed.data[key];
703
707
  }
@@ -1233,7 +1237,8 @@ var BackgroundLogger = class _BackgroundLogger {
1233
1237
  numDropped: 0,
1234
1238
  lastLoggedTimestamp: 0
1235
1239
  };
1236
- constructor(apiConn) {
1240
+ constructor(apiConn, opts) {
1241
+ opts = opts ?? {};
1237
1242
  this.apiConn = apiConn;
1238
1243
  const syncFlushEnv = Number(isomorph_default.getEnv("BRAINTRUST_SYNC_FLUSH"));
1239
1244
  if (!isNaN(syncFlushEnv)) {
@@ -1277,9 +1282,11 @@ var BackgroundLogger = class _BackgroundLogger {
1277
1282
  if (allPublishPayloadsDirEnv) {
1278
1283
  this.allPublishPayloadsDir = allPublishPayloadsDirEnv;
1279
1284
  }
1280
- isomorph_default.processOn("beforeExit", async () => {
1281
- await this.flush();
1282
- });
1285
+ if (!opts.noExitFlush) {
1286
+ isomorph_default.processOn("beforeExit", async () => {
1287
+ await this.flush();
1288
+ });
1289
+ }
1283
1290
  }
1284
1291
  log(items) {
1285
1292
  const [addedItems, droppedItems] = (() => {
package/dist/index.mjs CHANGED
@@ -538,10 +538,11 @@ var loginSchema = z2.strictObject({
538
538
  orgId: z2.string().nullish(),
539
539
  gitMetadataSettings: gitMetadataSettingsSchema.nullish()
540
540
  });
541
+ var stateNonce = 0;
541
542
  var BraintrustState = class _BraintrustState {
542
543
  constructor(loginParams) {
543
544
  this.loginParams = loginParams;
544
- this.id = (/* @__PURE__ */ new Date()).toLocaleString();
545
+ this.id = `${(/* @__PURE__ */ new Date()).toLocaleString()}-${stateNonce++}`;
545
546
  this.currentExperiment = void 0;
546
547
  this.currentLogger = void 0;
547
548
  this.currentSpan = isomorph_default.newAsyncLocalStorage();
@@ -552,7 +553,10 @@ var BraintrustState = class _BraintrustState {
552
553
  await this.login({});
553
554
  return this.apiConn();
554
555
  };
555
- this._bgLogger = new BackgroundLogger(new LazyValue(defaultGetLogConn));
556
+ this._bgLogger = new BackgroundLogger(
557
+ new LazyValue(defaultGetLogConn),
558
+ loginParams
559
+ );
556
560
  this.resetLoginInfo();
557
561
  }
558
562
  id;
@@ -629,14 +633,14 @@ var BraintrustState = class _BraintrustState {
629
633
  gitMetadataSettings: this.gitMetadataSettings
630
634
  };
631
635
  }
632
- static deserialize(serialized) {
636
+ static deserialize(serialized, opts) {
633
637
  const serializedParsed = loginSchema.safeParse(serialized);
634
638
  if (!serializedParsed.success) {
635
639
  throw new Error(
636
640
  `Cannot deserialize BraintrustState: ${serializedParsed.error.errors}`
637
641
  );
638
642
  }
639
- const state = new _BraintrustState({});
643
+ const state = new _BraintrustState({ ...opts });
640
644
  for (const key of Object.keys(loginSchema.shape)) {
641
645
  state[key] = serializedParsed.data[key];
642
646
  }
@@ -1172,7 +1176,8 @@ var BackgroundLogger = class _BackgroundLogger {
1172
1176
  numDropped: 0,
1173
1177
  lastLoggedTimestamp: 0
1174
1178
  };
1175
- constructor(apiConn) {
1179
+ constructor(apiConn, opts) {
1180
+ opts = opts ?? {};
1176
1181
  this.apiConn = apiConn;
1177
1182
  const syncFlushEnv = Number(isomorph_default.getEnv("BRAINTRUST_SYNC_FLUSH"));
1178
1183
  if (!isNaN(syncFlushEnv)) {
@@ -1216,9 +1221,11 @@ var BackgroundLogger = class _BackgroundLogger {
1216
1221
  if (allPublishPayloadsDirEnv) {
1217
1222
  this.allPublishPayloadsDir = allPublishPayloadsDirEnv;
1218
1223
  }
1219
- isomorph_default.processOn("beforeExit", async () => {
1220
- await this.flush();
1221
- });
1224
+ if (!opts.noExitFlush) {
1225
+ isomorph_default.processOn("beforeExit", async () => {
1226
+ await this.flush();
1227
+ });
1228
+ }
1222
1229
  }
1223
1230
  log(items) {
1224
1231
  const [addedItems, droppedItems] = (() => {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "braintrust",
3
- "version": "0.0.142",
3
+ "version": "0.0.143",
4
4
  "description": "SDK for integrating Braintrust",
5
5
  "main": "./dist/index.js",
6
6
  "module": "./dist/index.mjs",