-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathlogger.ts
More file actions
7767 lines (7010 loc) · 241 KB
/
logger.ts
File metadata and controls
7767 lines (7010 loc) · 241 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/// <reference lib="dom" />
import { v4 as uuidv4 } from "uuid";
import { Queue, DEFAULT_QUEUE_SIZE } from "./queue";
import { IDGenerator, getIdGenerator } from "./id-gen";
import {
_urljoin,
AnyDatasetRecord,
AUDIT_METADATA_FIELD,
AUDIT_SOURCE_FIELD,
BackgroundLogEvent,
batchItems,
constructJsonArray,
DatasetRecord,
DEFAULT_IS_LEGACY_DATASET,
ensureDatasetRecord,
ExperimentEvent,
ExperimentLogFullArgs,
ExperimentLogPartialArgs,
IdField,
IS_MERGE_FIELD,
LogFeedbackFullArgs,
mergeDicts,
mergeGitMetadataSettings,
mergeRowBatch,
OBJECT_DELETE_FIELD,
OBJECT_ID_KEYS,
SanitizedExperimentLogPartialArgs,
SpanComponentsV3,
SpanComponentsV4,
SpanObjectTypeV3,
spanObjectTypeV3ToString,
SpanType,
SpanTypeAttribute,
TRANSACTION_ID_FIELD,
TransactionId,
VALID_SOURCES,
isArray,
isObject,
} from "../util/index";
import {
type AnyModelParamsType as AnyModelParam,
AttachmentReference as attachmentReferenceSchema,
type AttachmentReferenceType as AttachmentReference,
BraintrustAttachmentReference as BraintrustAttachmentReferenceSchema,
type BraintrustAttachmentReferenceType as BraintrustAttachmentReference,
BraintrustModelParams as braintrustModelParamsSchema,
ChatCompletionTool as chatCompletionToolSchema,
type ChatCompletionToolType as ChatCompletionTool,
ExternalAttachmentReference as ExternalAttachmentReferenceSchema,
type ExternalAttachmentReferenceType as ExternalAttachmentReference,
type ModelParamsType as ModelParams,
ResponseFormatJsonSchema as responseFormatJsonSchemaSchema,
AttachmentStatus as attachmentStatusSchema,
type AttachmentStatusType as AttachmentStatus,
GitMetadataSettings as gitMetadataSettingsSchema,
type GitMetadataSettingsType as GitMetadataSettings,
type ChatCompletionMessageParamType as Message,
type ChatCompletionOpenAIMessageParamType as OpenAIMessage,
PromptData as promptDataSchema,
type PromptDataType as PromptData,
Prompt as promptSchema,
type PromptType as PromptRow,
type PromptSessionEventType as PromptSessionEvent,
type RepoInfoType as RepoInfo,
type PromptBlockDataType as PromptBlockData,
} from "./generated_types";
const BRAINTRUST_ATTACHMENT =
BraintrustAttachmentReferenceSchema.shape.type.value;
const EXTERNAL_ATTACHMENT = ExternalAttachmentReferenceSchema.shape.type.value;
export const LOGS3_OVERFLOW_REFERENCE_TYPE = "logs3_overflow";
const BRAINTRUST_PARAMS = Object.keys(braintrustModelParamsSchema.shape);
// 6 MB for the AWS lambda gateway (from our own testing).
export const DEFAULT_MAX_REQUEST_SIZE = 6 * 1024 * 1024;
const parametersRowSchema = z.object({
id: z.string().uuid(),
_xact_id: z.string(),
project_id: z.string().uuid(),
name: z.string(),
slug: z.string(),
description: z.union([z.string(), z.null()]).optional(),
function_type: z.literal("parameters"),
function_data: z.object({
type: z.literal("parameters"),
data: z.record(z.unknown()).optional(),
__schema: z.record(z.unknown()),
}),
metadata: z
.union([z.object({}).partial().passthrough(), z.null()])
.optional(),
});
type ParametersRow = z.infer<typeof parametersRowSchema>;
import { waitUntil } from "@vercel/functions";
import Mustache from "mustache";
import {
parseTemplateFormat,
renderTemplateContent,
type TemplateFormat,
} from "./template/renderer";
import { renderNunjucksString } from "./template/nunjucks-env";
import { z, ZodError } from "zod/v3";
import {
BraintrustStream,
createFinalValuePassThroughStream,
devNullWritableStream,
} from "./functions/stream";
import iso, { IsoAsyncLocalStorage } from "./isomorph";
import { canUseDiskCache, DiskCache } from "./prompt-cache/disk-cache";
import { LRUCache } from "./prompt-cache/lru-cache";
import { PromptCache } from "./prompt-cache/prompt-cache";
import { ParametersCache } from "./prompt-cache/parameters-cache";
import {
addAzureBlobHeaders,
getCurrentUnixTimestamp,
GLOBAL_PROJECT,
isEmpty,
LazyValue,
SyncLazyValue,
runCatchFinally,
} from "./util";
import { lintTemplate as lintMustacheTemplate } from "./template/mustache-utils";
import { lintTemplate as lintNunjucksTemplate } from "./template/nunjucks-utils";
import { prettifyXact } from "../util/index";
import { SpanCache, CachedSpan } from "./span-cache";
import type { EvalParameters, InferParameters } from "./eval-parameters";
// Context management interfaces
export interface ContextParentSpanIds {
rootSpanId: string;
spanParents: string[];
}
export class LoginInvalidOrgError extends Error {
constructor(public message: string) {
super(message);
}
}
// Fields that should be passed to the masking function
// Note: "tags" field is intentionally excluded, but can be added if needed
const REDACTION_FIELDS = [
"input",
"output",
"expected",
"metadata",
"context",
"scores",
"metrics",
] as const;
class MaskingError {
constructor(
public readonly fieldName: string,
public readonly errorType: string,
) {}
get errorMsg(): string {
return `ERROR: Failed to mask field '${this.fieldName}' - ${this.errorType}`;
}
}
/**
* Apply masking function to data and handle errors gracefully.
* If the masking function raises an exception, returns an error message.
* Returns MaskingError for scores/metrics fields to signal they should be dropped.
*/
function applyMaskingToField(
maskingFunction: (value: unknown) => unknown,
data: unknown,
fieldName: string,
): unknown {
try {
return maskingFunction(data);
} catch (error) {
// Return a generic error message without the stack trace to avoid leaking PII
const errorType = error instanceof Error ? error.constructor.name : "Error";
// For scores and metrics fields, return a special error object
// to signal the field should be dropped and error logged
if (fieldName === "scores" || fieldName === "metrics") {
return new MaskingError(fieldName, errorType);
}
// For metadata field that expects object type, return an object with error key
if (fieldName === "metadata") {
return {
error: `ERROR: Failed to mask field '${fieldName}' - ${errorType}`,
};
}
// For other fields, return the error message as a string
return `ERROR: Failed to mask field '${fieldName}' - ${errorType}`;
}
}
export type SetCurrentArg = { setCurrent?: boolean };
type StartSpanEventArgs = ExperimentLogPartialArgs & Partial<IdField>;
export type StartSpanArgs = {
name?: string;
type?: SpanType;
// eslint-disable-next-line @typescript-eslint/no-explicit-any
spanAttributes?: Record<any, any>;
startTime?: number;
parent?: string;
event?: StartSpanEventArgs;
propagatedEvent?: StartSpanEventArgs;
spanId?: string;
parentSpanIds?: ParentSpanIds | MultiParentSpanIds;
};
export type EndSpanArgs = {
endTime?: number;
};
export interface Exportable {
/**
* Return a serialized representation of the object that can be used to start subspans in other places. See {@link Span.traced} for more details.
*/
export(): Promise<string>;
}
/**
* A Span encapsulates logged data and metrics for a unit of work. This interface is shared by all span implementations.
*
* We suggest using one of the various `traced` methods, instead of creating Spans directly. See {@link Span.traced} for full details.
*/
export interface Span extends Exportable {
/**
* Row ID of the span.
*/
id: string;
/**
* Span ID of the span.
*/
spanId: string;
/**
* Root span ID of the span.
*/
rootSpanId: string;
/**
* Parent span IDs of the span.
*/
spanParents: string[];
getParentInfo():
| {
objectType: SpanObjectTypeV3;
objectId: LazyValue<string>;
computeObjectMetadataArgs: Record<string, unknown> | undefined;
}
| undefined;
/**
* Incrementally update the current span with new data. The event will be batched and uploaded behind the scenes.
*
* @param event: Data to be logged. See {@link Experiment.log} for full details.
*/
log(event: ExperimentLogPartialArgs): void;
/**
* Add feedback to the current span. Unlike `Experiment.logFeedback` and `Logger.logFeedback`, this method does not accept an id parameter, because it logs feedback to the current span.
*
* @param event: Data to be logged. See {@link Experiment.logFeedback} for full details.
*/
logFeedback(event: Omit<LogFeedbackFullArgs, "id">): void;
/**
* Create a new span and run the provided callback. This is useful if you want to log more detailed trace information beyond the scope of a single log event. Data logged over several calls to `Span.log` will be merged into one logical row.
*
* Spans created within `traced` are ended automatically. By default, the span is marked as current, so they can be accessed using `braintrust.currentSpan`.
*
* @param callback The function to be run under the span context.
* @param args.name Optional name of the span. If not provided, a name will be inferred from the call stack.
* @param args.type Optional type of the span. If not provided, the type will be unset.
* @param args.span_attributes Optional additional attributes to attach to the span, such as a type name.
* @param args.start_time Optional start time of the span, as a timestamp in seconds.
* @param args.setCurrent If true (the default), the span will be marked as the currently-active span for the duration of the callback.
* @param args.parent Optional parent info string for the span. The string can be generated from `[Span,Experiment,Logger].export`. If not provided, the current span will be used (depending on context). This is useful for adding spans to an existing trace.
* @param args.event Data to be logged. See {@link Experiment.log} for full details.
* @returns The result of running `callback`.
*/
traced<R>(
callback: (span: Span) => R,
args?: StartSpanArgs & SetCurrentArg,
): R;
/**
* Lower-level alternative to `traced`. This allows you to start a span yourself, and can be useful in situations
* where you cannot use callbacks. However, spans started with `startSpan` will not be marked as the "current span",
* so `currentSpan()` and `traced()` will be no-ops. If you want to mark a span as current, use `traced` instead.
*
* See {@link Span.traced} for full details.
*
* @returns The newly-created `Span`
*/
startSpan(args?: StartSpanArgs): Span;
/**
* Log an end time to the span (defaults to the current time). Returns the logged time.
*
* Will be invoked automatically if the span is constructed with `traced`.
*
* @param args.endTime Optional end time of the span, as a timestamp in seconds.
* @returns The end time logged to the span metrics.
*/
end(args?: EndSpanArgs): number;
/**
* Serialize the identifiers of this span. The return value can be used to
* identify this span when starting a subspan elsewhere, such as another
* process or service, without needing to access this `Span` object. See the
* parameters of {@link Span.startSpan} for usage details.
*
* Callers should treat the return value as opaque. The serialization format
* may change from time to time. If parsing is needed, use
* `SpanComponentsV3.fromStr`.
*
* @returns Serialized representation of this span's identifiers.
*/
export(): Promise<string>;
/**
* Format a permalink to the Braintrust application for viewing this span.
*
* Links can be generated at any time, but they will only become viewable
* after the span and its root have been flushed to the server and ingested.
*
* This function can block resolving data with the server. For production
* applications it's preferable to call {@link Span.link} instead.
*
* @returns A promise which resolves to a permalink to the span.
*/
permalink(): Promise<string>;
/**
* Format a link to the Braintrust application for viewing this span.
*
* Links can be generated at any time, but they will only become viewable
* after the span and its root have been flushed to the server and ingested.
*
* There are some conditions when a Span doesn't have enough information
* to return a stable link (e.g. during an unresolved experiment). In this case
* or if there's an error generating link, we'll return a placeholder link.
*
* @returns A link to the span.
*/
link(): string;
/**
* Flush any pending rows to the server.
*/
flush(): Promise<void>;
/**
* Alias for `end`.
*/
close(args?: EndSpanArgs): number;
/**
* Set the span's name, type, or other attributes after it's created.
*/
setAttributes(args: Omit<StartSpanArgs, "event">): void;
/**
* Start a span with a specific id and parent span ids.
*/
startSpanWithParents(
spanId: string,
spanParents: string[],
args?: StartSpanArgs,
): Span;
/*
* Gets the span's `state` value, which is usually the global logging state (this is
* for very advanced purposes only)
*/
state(): BraintrustState;
// For type identification.
kind: "span";
}
export abstract class ContextManager {
abstract getParentSpanIds(): ContextParentSpanIds | undefined;
abstract runInContext<R>(span: Span, callback: () => R): R;
abstract getCurrentSpan(): Span | undefined;
}
class BraintrustContextManager extends ContextManager {
private _currentSpan: IsoAsyncLocalStorage<Span>;
constructor() {
super();
this._currentSpan = iso.newAsyncLocalStorage();
}
getParentSpanIds(): ContextParentSpanIds | undefined {
const currentSpan = this._currentSpan.getStore();
if (!currentSpan) {
return undefined;
}
return {
rootSpanId: currentSpan.rootSpanId,
spanParents: [currentSpan.spanId],
};
}
runInContext<R>(span: Span, callback: () => R): R {
return this._currentSpan.run(span, callback);
}
getCurrentSpan(): Span | undefined {
return this._currentSpan.getStore();
}
}
// make sure to update @braintrust/otel package
declare global {
var BRAINTRUST_CONTEXT_MANAGER: (new () => ContextManager) | undefined;
var BRAINTRUST_ID_GENERATOR: (new () => IDGenerator) | undefined;
var BRAINTRUST_SPAN_COMPONENT: SpanComponent | undefined;
}
type SpanComponent = typeof SpanComponentsV3 | typeof SpanComponentsV4;
function getSpanComponentsClass(): SpanComponent {
return globalThis.BRAINTRUST_SPAN_COMPONENT
? globalThis.BRAINTRUST_SPAN_COMPONENT
: SpanComponentsV3;
}
export function getContextManager(): ContextManager {
return globalThis.BRAINTRUST_CONTEXT_MANAGER
? new globalThis.BRAINTRUST_CONTEXT_MANAGER()
: new BraintrustContextManager();
}
/**
* A fake implementation of the Span API which does nothing. This can be used as the default span.
*/
export class NoopSpan implements Span {
public id: string;
public spanId: string;
public rootSpanId: string;
public spanParents: string[];
public kind: "span" = "span" as const;
constructor() {
this.id = "";
this.spanId = "";
this.rootSpanId = "";
this.spanParents = [];
}
public log(_: ExperimentLogPartialArgs) {}
public logFeedback(_event: Omit<LogFeedbackFullArgs, "id">) {}
public traced<R>(
callback: (span: Span) => R,
_1?: StartSpanArgs & SetCurrentArg,
): R {
return callback(this);
}
public getParentInfo() {
return undefined;
}
public startSpan(_1?: StartSpanArgs) {
return this;
}
public end(args?: EndSpanArgs): number {
return args?.endTime ?? getCurrentUnixTimestamp();
}
public async export(): Promise<string> {
return "";
}
public async permalink(): Promise<string> {
return NOOP_SPAN_PERMALINK;
}
public link(): string {
return NOOP_SPAN_PERMALINK;
}
public async flush(): Promise<void> {}
public close(args?: EndSpanArgs): number {
return this.end(args);
}
public setAttributes(_args: Omit<StartSpanArgs, "event">) {}
public startSpanWithParents(
_spanId: string,
_spanParents: string[],
_args?: StartSpanArgs,
): Span {
return this;
}
public state() {
return _internalGetGlobalState();
}
// Custom inspect for Node.js console.log
[Symbol.for("nodejs.util.inspect.custom")](): string {
return `NoopSpan {
kind: '${this.kind}',
id: '${this.id}',
spanId: '${this.spanId}',
rootSpanId: '${this.rootSpanId}',
spanParents: ${JSON.stringify(this.spanParents)}
}`;
}
// Custom toString
toString(): string {
return `NoopSpan(id=${this.id}, spanId=${this.spanId})`;
}
}
export const NOOP_SPAN = new NoopSpan();
export const NOOP_SPAN_PERMALINK = "https://braintrust.dev/noop-span";
// In certain situations (e.g. the cli), we want separately-compiled modules to
// use the same state as the toplevel module. This global variable serves as a
// mechanism to propagate the initial state from some toplevel creator.
declare global {
var __inherited_braintrust_state: BraintrustState;
}
const loginSchema = z.strictObject({
appUrl: z.string(),
appPublicUrl: z.string(),
orgName: z.string(),
apiUrl: z.string(),
proxyUrl: z.string(),
loginToken: z.string(),
orgId: z.string().nullish(),
gitMetadataSettings: gitMetadataSettingsSchema.nullish(),
});
export type SerializedBraintrustState = z.infer<typeof loginSchema>;
let stateNonce = 0;
export class BraintrustState {
public id: string;
public currentExperiment: Experiment | undefined;
// Note: the value of IsAsyncFlush doesn't really matter here, since we
// (safely) dynamically cast it whenever retrieving the logger.
public currentLogger: Logger<false> | undefined;
public currentParent: IsoAsyncLocalStorage<string>;
public currentSpan: IsoAsyncLocalStorage<Span>;
// Any time we re-log in, we directly update the apiConn inside the logger.
// This is preferable to replacing the whole logger, which would create the
// possibility of multiple loggers floating around, which may not log in a
// deterministic order.
private _bgLogger: SyncLazyValue<HTTPBackgroundLogger>;
private _overrideBgLogger: BackgroundLogger | null = null;
public appUrl: string | null = null;
public appPublicUrl: string | null = null;
public loginToken: string | null = null;
public orgId: string | null = null;
public orgName: string | null = null;
public apiUrl: string | null = null;
public proxyUrl: string | null = null;
public loggedIn: boolean = false;
public gitMetadataSettings?: GitMetadataSettings;
public fetch: typeof globalThis.fetch = globalThis.fetch;
private _appConn: HTTPConnection | null = null;
private _apiConn: HTTPConnection | null = null;
private _proxyConn: HTTPConnection | null = null;
public promptCache: PromptCache;
public parametersCache: ParametersCache;
public spanCache: SpanCache;
private _idGenerator: IDGenerator | null = null;
private _contextManager: ContextManager | null = null;
private _otelFlushCallback: (() => Promise<void>) | null = null;
constructor(private loginParams: LoginOptions) {
this.id = `${new Date().toLocaleString()}-${stateNonce++}`; // This is for debugging. uuidv4() breaks on platforms like Cloudflare.
this.currentExperiment = undefined;
this.currentLogger = undefined;
this.currentParent = iso.newAsyncLocalStorage();
this.currentSpan = iso.newAsyncLocalStorage();
if (loginParams.fetch) {
this.fetch = loginParams.fetch;
}
const defaultGetLogConn = async () => {
await this.login({});
return this.apiConn();
};
this._bgLogger = new SyncLazyValue(
() =>
new HTTPBackgroundLogger(new LazyValue(defaultGetLogConn), loginParams),
);
this.resetLoginInfo();
const memoryCache = new LRUCache<string, Prompt>({
max: Number(iso.getEnv("BRAINTRUST_PROMPT_CACHE_MEMORY_MAX")) ?? 1 << 10,
});
const diskCache = canUseDiskCache()
? new DiskCache<Prompt>({
cacheDir:
iso.getEnv("BRAINTRUST_PROMPT_CACHE_DIR") ??
`${iso.getEnv("HOME") ?? iso.homedir!()}/.braintrust/prompt_cache`,
max:
Number(iso.getEnv("BRAINTRUST_PROMPT_CACHE_DISK_MAX")) ?? 1 << 20,
})
: undefined;
this.promptCache = new PromptCache({ memoryCache, diskCache });
const parametersMemoryCache = new LRUCache<string, RemoteEvalParameters>({
max:
Number(iso.getEnv("BRAINTRUST_PARAMETERS_CACHE_MEMORY_MAX")) ?? 1 << 10,
});
const parametersDiskCache = canUseDiskCache()
? new DiskCache<RemoteEvalParameters>({
cacheDir:
iso.getEnv("BRAINTRUST_PARAMETERS_CACHE_DIR") ??
`${iso.getEnv("HOME") ?? iso.homedir!()}/.braintrust/parameters_cache`,
max:
Number(iso.getEnv("BRAINTRUST_PARAMETERS_CACHE_DISK_MAX")) ??
1 << 20,
})
: undefined;
this.parametersCache = new ParametersCache({
memoryCache: parametersMemoryCache,
diskCache: parametersDiskCache,
});
this.spanCache = new SpanCache({ disabled: loginParams.disableSpanCache });
}
public resetLoginInfo() {
this.appUrl = null;
this.appPublicUrl = null;
this.loginToken = null;
this.orgId = null;
this.orgName = null;
this.apiUrl = null;
this.proxyUrl = null;
this.loggedIn = false;
this.gitMetadataSettings = undefined;
this._appConn = null;
this._apiConn = null;
this._proxyConn = null;
}
public resetIdGenState() {
// Reset the ID generator so it gets recreated with current environment variables
this._idGenerator = null;
}
public get idGenerator(): IDGenerator {
if (this._idGenerator === null) {
this._idGenerator = getIdGenerator();
}
return this._idGenerator;
}
public get contextManager(): ContextManager {
if (this._contextManager === null) {
this._contextManager = getContextManager();
}
return this._contextManager;
}
/**
* Register an OTEL flush callback. This is called by @braintrust/otel
* when it initializes a BraintrustSpanProcessor/Exporter.
*/
public registerOtelFlush(callback: () => Promise<void>): void {
this._otelFlushCallback = callback;
}
/**
* Flush OTEL spans if a callback is registered.
* Called during ensureSpansFlushed to ensure OTEL spans are visible in BTQL.
*/
public async flushOtel(): Promise<void> {
if (this._otelFlushCallback) {
await this._otelFlushCallback();
}
}
public copyLoginInfo(other: BraintrustState) {
this.appUrl = other.appUrl;
this.appPublicUrl = other.appPublicUrl;
this.loginToken = other.loginToken;
this.orgId = other.orgId;
this.orgName = other.orgName;
this.apiUrl = other.apiUrl;
this.proxyUrl = other.proxyUrl;
this.loggedIn = other.loggedIn;
this.gitMetadataSettings = other.gitMetadataSettings;
this._appConn = other._appConn;
this._apiConn = other._apiConn;
this.loginReplaceApiConn(this.apiConn());
this._proxyConn = other._proxyConn;
}
public serialize(): SerializedBraintrustState {
if (!this.loggedIn) {
throw new Error(
"Cannot serialize BraintrustState without being logged in",
);
}
if (
!this.appUrl ||
!this.appPublicUrl ||
!this.apiUrl ||
!this.proxyUrl ||
!this.orgName ||
!this.loginToken ||
!this.loggedIn
) {
throw new Error(
"Cannot serialize BraintrustState without all login attributes",
);
}
return {
appUrl: this.appUrl,
appPublicUrl: this.appPublicUrl,
loginToken: this.loginToken,
orgId: this.orgId,
orgName: this.orgName,
apiUrl: this.apiUrl,
proxyUrl: this.proxyUrl,
gitMetadataSettings: this.gitMetadataSettings,
};
}
static deserialize(
serialized: unknown,
opts?: LoginOptions,
): BraintrustState {
const serializedParsed = loginSchema.safeParse(serialized);
if (!serializedParsed.success) {
throw new Error(
`Cannot deserialize BraintrustState: ${serializedParsed.error.message}`,
);
}
const state = new BraintrustState({ ...opts });
for (const key of Object.keys(loginSchema.shape)) {
(state as any)[key] = (serializedParsed.data as any)[key];
}
if (!state.loginToken) {
throw new Error(
"Cannot deserialize BraintrustState without a login token",
);
}
state.apiConn().set_token(state.loginToken);
state.apiConn().make_long_lived();
state.appConn().set_token(state.loginToken);
if (state.proxyUrl) {
state.proxyConn().make_long_lived();
state.proxyConn().set_token(state.loginToken);
}
state.loggedIn = true;
state.loginReplaceApiConn(state.apiConn());
return state;
}
public setFetch(fetch: typeof globalThis.fetch) {
this.loginParams.fetch = fetch;
this.fetch = fetch;
this._apiConn?.setFetch(fetch);
this._appConn?.setFetch(fetch);
}
public setMaskingFunction(
maskingFunction: ((value: unknown) => unknown) | null,
): void {
this.bgLogger().setMaskingFunction(maskingFunction);
}
public async login(loginParams: LoginOptions & { forceLogin?: boolean }) {
if (this.apiUrl && !loginParams.forceLogin) {
return;
}
const newState = await loginToState({
...this.loginParams,
...Object.fromEntries(
Object.entries(loginParams).filter(([k, v]) => !isEmpty(v)),
),
});
this.copyLoginInfo(newState);
}
public appConn(): HTTPConnection {
if (!this._appConn) {
if (!this.appUrl) {
throw new Error("Must initialize appUrl before requesting appConn");
}
this._appConn = new HTTPConnection(this.appUrl, this.fetch);
}
return this._appConn!;
}
public apiConn(): HTTPConnection {
if (!this._apiConn) {
if (!this.apiUrl) {
throw new Error("Must initialize apiUrl before requesting apiConn");
}
this._apiConn = new HTTPConnection(this.apiUrl, this.fetch);
}
return this._apiConn!;
}
public proxyConn(): HTTPConnection {
if (!this.proxyUrl) {
return this.apiConn();
}
if (!this._proxyConn) {
if (!this.proxyUrl) {
throw new Error("Must initialize proxyUrl before requesting proxyConn");
}
this._proxyConn = new HTTPConnection(this.proxyUrl, this.fetch);
}
return this._proxyConn!;
}
public bgLogger(): BackgroundLogger {
if (this._overrideBgLogger) {
return this._overrideBgLogger;
}
return this._bgLogger.get();
}
public httpLogger(): HTTPBackgroundLogger {
// this is called for configuration in some end-to-end tests so
// expose the http bg logger here.
return this._bgLogger.get() as HTTPBackgroundLogger;
}
public setOverrideBgLogger(logger: BackgroundLogger | null) {
this._overrideBgLogger = logger;
}
// Should only be called by the login function.
public loginReplaceApiConn(apiConn: HTTPConnection) {
this._bgLogger.get().internalReplaceApiConn(apiConn);
}
public disable() {
this._bgLogger.get().disable();
}
public enforceQueueSizeLimit(enforce: boolean) {
this._bgLogger.get().enforceQueueSizeLimit(enforce);
}
// Custom serialization to avoid logging sensitive data
toJSON(): Record<string, any> {
return {
id: this.id,
orgId: this.orgId,
orgName: this.orgName,
appUrl: this.appUrl,
appPublicUrl: this.appPublicUrl,
apiUrl: this.apiUrl,
proxyUrl: this.proxyUrl,
loggedIn: this.loggedIn,
// Explicitly exclude loginToken, _apiConn, _appConn, _proxyConn and other sensitive fields
};
}
// Custom inspect for Node.js console.log
[Symbol.for("nodejs.util.inspect.custom")](): string {
return `BraintrustState {
id: '${this.id}',
orgId: ${this.orgId ? `'${this.orgId}'` : "null"},
orgName: ${this.orgName ? `'${this.orgName}'` : "null"},
appUrl: ${this.appUrl ? `'${this.appUrl}'` : "null"},
apiUrl: ${this.apiUrl ? `'${this.apiUrl}'` : "null"},
proxyUrl: ${this.proxyUrl ? `'${this.proxyUrl}'` : "null"},
loggedIn: ${this.loggedIn},
loginToken: '[REDACTED]'
}`;
}
// Custom toString
toString(): string {
return `BraintrustState(id=${this.id}, org=${this.orgName || "none"}, loggedIn=${this.loggedIn})`;
}
}
let _globalState: BraintrustState;
// Return a TestBackgroundLogger that will intercept logs before they are sent to the server.
// Used for testing only.
function useTestBackgroundLogger(): TestBackgroundLogger {
const state = _internalGetGlobalState();
if (!state) {
throw new Error("global state not set yet");
}
const logger = new TestBackgroundLogger();
state.setOverrideBgLogger(logger);
return logger;
}
function clearTestBackgroundLogger() {
_internalGetGlobalState()?.setOverrideBgLogger(null);
}
// Initialize a test Experiment without making network calls by injecting fake metadata.
// Useful for unit tests that need an Experiment instance.
function initTestExperiment(
experimentName: string,
projectName?: string,
): Experiment {
setInitialTestState();
const state = _internalGetGlobalState();
const project = projectName ?? experimentName;
const lazyMetadata: LazyValue<ProjectExperimentMetadata> = new LazyValue(
async () => ({
project: { id: project, name: project, fullInfo: {} },
experiment: { id: experimentName, name: experimentName, fullInfo: {} },
}),
);
return new Experiment(state, lazyMetadata);
}
/**
* This function should be invoked exactly once after configuring the `iso`
* object based on the platform. See js/src/node.ts for an example.
* @internal
*/
export function _internalSetInitialState() {
if (_globalState) {
console.warn(
"global state already set, should only call _internalSetInitialState once",
);
return;
}
_globalState =
globalThis.__inherited_braintrust_state ||
new BraintrustState({
/*empty login options*/
});
}
/**
* @internal
*/
export const _internalGetGlobalState = () => _globalState;
/**
* Register a callback to flush OTEL spans. This is called by @braintrust/otel
* when it initializes a BraintrustSpanProcessor/Exporter.
*
* When ensureSpansFlushed is called (e.g., before a BTQL query in scorers),
* this callback will be invoked to ensure OTEL spans are flushed to the server.
*
* Also disables the span cache, since OTEL spans aren't in the local cache
* and we need BTQL to see the complete span tree (both native + OTEL spans).
*/
export function registerOtelFlush(callback: () => Promise<void>): void {
_globalState?.registerOtelFlush(callback);
// Disable span cache since OTEL spans aren't in the local cache
_globalState?.spanCache?.disable();
}
export class FailedHTTPResponse extends Error {
public status: number;