-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathlogger.py
More file actions
5942 lines (4934 loc) · 230 KB
/
logger.py
File metadata and controls
5942 lines (4934 loc) · 230 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
import asyncio
import atexit
import base64
import concurrent.futures
import contextlib
import contextvars
import dataclasses
import datetime
import inspect
import io
import json
import logging
import os
import sys
import textwrap
import threading
import time
import traceback
import types
import uuid
from abc import ABC, abstractmethod
from collections.abc import Callable, Iterator, Mapping, MutableMapping, Sequence
from functools import partial, wraps
from multiprocessing import cpu_count
from types import TracebackType
from typing import (
Any,
Dict,
Generic,
Literal,
Optional,
TypedDict,
TypeVar,
Union,
cast,
overload,
)
from urllib.error import HTTPError, URLError
from urllib.parse import urlencode
from urllib.request import Request, urlopen
import chevron
import exceptiongroup
import requests
import urllib3
from braintrust.functions.stream import BraintrustStream
from requests.adapters import HTTPAdapter
from urllib3.util.retry import Retry
from . import context, id_gen
from .bt_json import bt_dumps, bt_safe_deep_copy
from .db_fields import (
AUDIT_METADATA_FIELD,
AUDIT_SOURCE_FIELD,
IS_MERGE_FIELD,
OBJECT_DELETE_FIELD,
OBJECT_ID_KEYS,
TRANSACTION_ID_FIELD,
VALID_SOURCES,
)
from .generated_types import (
AttachmentReference,
AttachmentStatus,
DatasetEvent,
ExperimentEvent,
PromptOptions,
SpanAttributes,
)
from .git_fields import GitMetadataSettings, RepoInfo
from .gitutil import get_past_n_ancestors, get_repo_info
from .merge_row_batch import batch_items, merge_row_batch
from .object import DEFAULT_IS_LEGACY_DATASET, ensure_dataset_record
from .parameters import RemoteEvalParameters
from .prompt import BRAINTRUST_PARAMS, ImagePart, PromptBlockData, PromptData, PromptMessage, PromptSchema, TextPart
from .prompt_cache.disk_cache import DiskCache
from .prompt_cache.lru_cache import LRUCache
from .prompt_cache.parameters_cache import ParametersCache
from .prompt_cache.prompt_cache import PromptCache
from .queue import DEFAULT_QUEUE_SIZE, LogQueue
from .serializable_data_class import SerializableDataClass
from .span_identifier_v3 import SpanComponentsV3, SpanObjectTypeV3
from .span_identifier_v4 import SpanComponentsV4
from .span_types import SpanTypeAttribute
from .types import Metadata
from .util import (
GLOBAL_PROJECT,
AugmentedHTTPError,
LazyValue,
_urljoin,
add_azure_blob_headers,
bt_iscoroutinefunction,
coalesce,
encode_uri_component,
eprint,
get_caller_location,
mask_api_key,
merge_dicts,
parse_env_var_float,
response_raise_for_status,
)
from .xact_ids import prettify_xact
# Fields that should be passed to the masking function
# Note: "tags" field is intentionally excluded, but can be added if needed
REDACTION_FIELDS = ["input", "output", "expected", "metadata", "context", "scores", "metrics"]
DATA_API_VERSION = 2
LOGS3_OVERFLOW_REFERENCE_TYPE = "logs3_overflow"
# 6 MB for the AWS lambda gateway (from our own testing).
DEFAULT_MAX_REQUEST_SIZE = 6 * 1024 * 1024
@dataclasses.dataclass
class Logs3OverflowInputRow:
object_ids: dict[str, Any]
has_comment: bool
is_delete: bool
byte_size: int
@dataclasses.dataclass
class LogItemWithMeta:
str_value: str
overflow_meta: Logs3OverflowInputRow
class DatasetRef(TypedDict, total=False):
"""Reference to a dataset by ID and optional version."""
id: str
version: str
class ParametersRef(TypedDict, total=False):
"""Reference to saved parameters by ID and optional version."""
id: str
version: str
T = TypeVar("T")
TMapping = TypeVar("TMapping", bound=Mapping[str, Any])
TMutableMapping = TypeVar("TMutableMapping", bound=MutableMapping[str, Any])
TEST_API_KEY = "___TEST_API_KEY__"
DEFAULT_APP_URL = "https://www.braintrust.dev"
def _get_exporter():
"""Return the active exporter (e.g. the version of SpanComponentsv*)"""
use_v4 = os.getenv("BRAINTRUST_OTEL_COMPAT", "false").lower() == "true"
return SpanComponentsV4 if use_v4 else SpanComponentsV3
class Exportable(ABC):
@abstractmethod
def export(self) -> str:
"""Return a serialized representation of the object that can be used to start subspans in other places. See `Span.start_span` for more details."""
class Span(Exportable, contextlib.AbstractContextManager, ABC):
"""
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 `start_span` methods, instead of creating Spans directly. See `Span.start_span` for full details.
"""
@property
@abstractmethod
def id(self) -> str:
"""Row ID of the span."""
@property
@abstractmethod
def name(self) -> str:
"""Name of the span, for display purposes only."""
@abstractmethod
def log(self, **event: Any) -> None:
"""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 `Experiment.log` for full details.
"""
@abstractmethod
def log_feedback(self, **event: Any) -> None:
"""Add feedback to the current span. Unlike `Experiment.log_feedback` and `Logger.log_feedback`, this method does not accept an id parameter, because it logs feedback to the current span.
:param **event: Data to be logged. See `Experiment.log_feedback` for full details.
"""
@abstractmethod
def start_span(
self,
name: str | None = None,
type: SpanTypeAttribute | None = None,
span_attributes: SpanAttributes | Mapping[str, Any] | None = None,
start_time: float | None = None,
set_current: bool | None = None,
parent: str | None = None,
**event: Any,
) -> "Span":
"""Create a new span. 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.
We recommend running spans within context managers (`with start_span(...) as span`) to automatically mark them as current and ensure they are ended. Only spans run within a context manager will be marked current, so they can be accessed using `braintrust.current_span()`. If you wish to start a span outside a context manager, be sure to end it with `span.end()`.
:param name: Optional name of the span. If not provided, a name will be inferred from the call stack.
:param type: Optional type of the span. Use the `SpanTypeAttribute` enum or just provide a string directly.
If not provided, the type will be unset.
:param span_attributes: Optional additional attributes to attach to the span, such as a type name.
:param start_time: Optional start time of the span, as a timestamp in seconds.
:param set_current: If true (the default), the span will be marked as the currently-active span for the duration of the context manager.
:param 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 **event: Data to be logged. See `Experiment.log` for full details.
:returns: The newly-created `Span`
"""
@abstractmethod
def export(self) -> str:
"""
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 `Span.start_span` 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 `SpanComponentsV4.from_str`.
:returns: Serialized representation of this span's identifiers.
"""
@abstractmethod
def link(self) -> str:
"""
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.
"""
@abstractmethod
def permalink(self) -> str:
"""
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 `Span.link` instead.
:returns: A permalink to the span.
"""
@abstractmethod
def end(self, end_time: float | None = None) -> float:
"""Log an end time to the span (defaults to the current time). Returns the logged time.
Will be invoked automatically if the span is bound to a context manager.
:param end_time: Optional end time of the span, as a timestamp in seconds.
:returns: The end time logged to the span metrics.
"""
@abstractmethod
def flush(self) -> None:
"""Flush any pending rows to the server."""
@abstractmethod
def close(self, end_time: float | None = None) -> float:
"""Alias for `end`."""
@abstractmethod
def set_attributes(
self,
name: str | None = None,
type: SpanTypeAttribute | None = None,
span_attributes: SpanAttributes | Mapping[str, Any] | None = None,
) -> None:
"""Set the span's name, type, or other attributes. These attributes will be attached to all log events within the span.
The attributes are equivalent to the arguments to start_span.
:param name: Optional name of the span. If not provided, a name will be inferred from the call stack.
:param type: Optional type of the span. Use the `SpanTypeAttribute` enum or just provide a string directly.
If not provided, the type will be unset.
:param span_attributes: Optional additional attributes to attach to the span, such as a type name.
"""
pass
@abstractmethod
def set_current(self) -> None:
"""Set the span as the current span. This is used to mark the span as the active span for the current thread."""
pass
@abstractmethod
def unset_current(self) -> None:
"""Unset the span as the current span."""
pass
class _NoopSpan(Span):
"""A fake implementation of the Span API which does nothing. This can be used as the default span."""
def __init__(self, *args: Any, **kwargs: Any):
pass
@property
def id(self):
return ""
@property
def name(self):
return ""
@property
def propagated_event(self):
return None
def log(self, **event: Any):
pass
def log_feedback(self, **event: Any):
pass
def start_span(
self,
name: str | None = None,
type: SpanTypeAttribute | None = None,
span_attributes: SpanAttributes | Mapping[str, Any] | None = None,
start_time: float | None = None,
set_current: bool | None = None,
parent: str | None = None,
**event: Any,
):
return self
def end(self, end_time: float | None = None) -> float:
return end_time or time.time()
def export(self):
return ""
def link(self) -> str:
return NOOP_SPAN_PERMALINK
def permalink(self) -> str:
return NOOP_SPAN_PERMALINK
def flush(self):
pass
def close(self, end_time: float | None = None) -> float:
return self.end(end_time)
def set_attributes(
self,
name: str | None = None,
type: SpanTypeAttribute | None = None,
span_attributes: SpanAttributes | Mapping[str, Any] | None = None,
):
pass
def set_current(self):
pass
def unset_current(self):
pass
def __enter__(self):
return super().__enter__()
def __exit__(
self,
exc_type: type[BaseException] | None,
exc_value: BaseException | None,
traceback: TracebackType | None,
):
pass
NOOP_SPAN: Span = _NoopSpan()
NOOP_SPAN_PERMALINK = "https://www.braintrust.dev/noop-span"
class BraintrustState:
def __init__(self):
self.id = str(uuid.uuid4())
self.current_experiment: Experiment | None = None
# We use both a ContextVar and a plain attribute for the current logger:
# - _cv_logger (ContextVar): Provides async context isolation so different
# async tasks can have different loggers without affecting each other.
# - _local_logger (plain attribute): Fallback for threads, since ContextVars
# don't propagate to new threads. This way if users don't want to do
# anything specific they'll always have a "global logger"
self._cv_logger: contextvars.ContextVar[Logger | None] = contextvars.ContextVar(
"braintrust_current_logger", default=None
)
self._local_logger: Logger | None = None
self.current_parent: contextvars.ContextVar[str | None] = contextvars.ContextVar(
"braintrust_current_parent", default=None
)
self.current_span: contextvars.ContextVar[Span] = contextvars.ContextVar(
"braintrust_current_span", default=NOOP_SPAN
)
# Context manager is dynamically selected based on current environment
self._context_manager = None
self._context_manager_lock = threading.Lock()
def default_get_api_conn():
self.login()
return self.api_conn()
# Any time we re-log in, we directly update the api_conn inside the
# logger. This is preferable to replacing the whole logger, which would
# create the possibility of multiple loggers floating around.
#
# We lazily-initialize the logger so that it does any initialization
# (including reading env variables) upon the first actual usage.
self._global_bg_logger = LazyValue(
lambda: _HTTPBackgroundLogger(LazyValue(default_get_api_conn, use_mutex=True)), use_mutex=True
)
self._id_generator = None
# For unit-testing, tests may wish to temporarily override the global
# logger with a custom one. We allow this but keep the override variable
# thread-local to prevent the possibility that tests running on
# different threads unintentionally use the same override.
self._override_bg_logger = threading.local()
self.reset_login_info()
self._prompt_cache = PromptCache(
memory_cache=LRUCache(
max_size=int(os.environ.get("BRAINTRUST_PROMPT_CACHE_MEMORY_MAX_SIZE", str(1 << 10)))
),
disk_cache=DiskCache(
cache_dir=os.environ.get(
"BRAINTRUST_PROMPT_CACHE_DIR", f"{os.environ.get('HOME')}/.braintrust/prompt_cache"
),
max_size=int(os.environ.get("BRAINTRUST_PROMPT_CACHE_DISK_MAX_SIZE", str(1 << 20))),
serializer=lambda x: x.as_dict(),
deserializer=PromptSchema.from_dict_deep,
),
)
self._parameters_cache = ParametersCache(
memory_cache=LRUCache(
max_size=int(os.environ.get("BRAINTRUST_PARAMETERS_CACHE_MEMORY_MAX_SIZE", str(1 << 10)))
),
disk_cache=DiskCache(
cache_dir=os.environ.get(
"BRAINTRUST_PARAMETERS_CACHE_DIR", f"{os.environ.get('HOME')}/.braintrust/parameters_cache"
),
max_size=int(os.environ.get("BRAINTRUST_PARAMETERS_CACHE_DISK_MAX_SIZE", str(1 << 20))),
serializer=lambda x: x.as_dict(),
deserializer=RemoteEvalParameters.from_dict_deep,
),
)
from braintrust.span_cache import SpanCache
self.span_cache = SpanCache()
self._otel_flush_callback: Any | None = None
def reset_login_info(self):
self.app_url: str | None = None
self.app_public_url: str | None = None
self.login_token: str | None = None
self.org_id: str | None = None
self.org_name: str | None = None
self.api_url: str | None = None
self.proxy_url: str | None = None
self.logged_in: bool = False
self.git_metadata_settings: GitMetadataSettings | None = None
self._app_conn: HTTPConnection | None = None
self._api_conn: HTTPConnection | None = None
self._proxy_conn: HTTPConnection | None = None
self._user_info: Mapping[str, Any] | None = None
def reset_parent_state(self):
# reset possible parent state for tests
self.current_experiment = None
self._cv_logger.set(None)
self._local_logger = None
self.current_parent.set(None)
self.current_span.set(NOOP_SPAN)
def _reset_id_generator(self):
# used in tests when we want to test with a different id generators
# which are controlled by env vars.
self._id_generator = None
def _reset_context_manager(self):
# used in tests when we want to test with a different context manager
# which is controlled by BRAINTRUST_OTEL_COMPAT env var.
self._context_manager = None
@property
def id_generator(self):
"""Return the active id generator."""
# While we probably only need one id generator per process (and it's configured with env vars), it's part of state
# so that we could possibly have parallel tests using different id generators.
if self._id_generator is None:
self._id_generator = id_gen.get_id_generator()
return self._id_generator
@property
def context_manager(self):
"""Get the appropriate context manager based on current environment."""
# Cache the context manager on first access
if self._context_manager is None:
with self._context_manager_lock:
# Double-check after acquiring lock
if self._context_manager is None:
from braintrust.context import get_context_manager
self._context_manager = get_context_manager()
return self._context_manager
def register_otel_flush(self, callback: Any) -> None:
"""
Register an OTEL flush callback. This is called by the OTEL integration
when it initializes a span processor/exporter.
"""
self._otel_flush_callback = callback
async def flush_otel(self) -> None:
"""
Flush OTEL spans if a callback is registered.
Called during ensure_spans_flushed to ensure OTEL spans are visible in BTQL.
"""
if self._otel_flush_callback:
await self._otel_flush_callback()
def copy_state(self, other: "BraintrustState"):
"""Copy login information from another BraintrustState instance."""
self.__dict__.update(
{
k: v
for (k, v) in other.__dict__.items()
if k
not in (
"current_experiment",
"_cv_logger",
"_local_logger",
"current_parent",
"current_span",
"_global_bg_logger",
"_override_bg_logger",
"_context_manager",
"_last_otel_setting",
"_context_manager_lock",
)
}
)
def login(
self,
app_url: str | None = None,
api_key: str | None = None,
org_name: str | None = None,
force_login: bool = False,
) -> None:
if not force_login and self.logged_in:
# We have already logged in. If any provided login inputs disagree
# with our existing settings, raise an Exception warning the user to
# try again with `force_login=True`.
def check_updated_param(varname, arg, orig):
if arg is not None and orig is not None and arg != orig:
raise Exception(
f"Re-logging in with different {varname} ({arg}) than original ({orig}). To force re-login, pass `force_login=True`"
)
sanitized_api_key = HTTPConnection.sanitize_token(api_key) if api_key else None
check_updated_param("app_url", app_url, self.app_url)
check_updated_param("api_key", sanitized_api_key, self.login_token)
check_updated_param("org_name", org_name, self.org_name)
return
state = login_to_state(
app_url=app_url,
api_key=api_key,
org_name=org_name,
)
self.copy_state(state)
def app_conn(self):
if not self._app_conn:
if not self.app_url:
raise RuntimeError("Must initialize app_url before requesting app_conn")
self._app_conn = HTTPConnection(self.app_url, adapter=_http_adapter)
return self._app_conn
def api_conn(self):
if not self._api_conn:
if not self.api_url:
raise RuntimeError("Must initialize api_url before requesting api_conn")
self._api_conn = HTTPConnection(self.api_url, adapter=_http_adapter)
return self._api_conn
def proxy_conn(self):
if not self.proxy_url:
return self.api_conn()
if not self._proxy_conn:
if not self.proxy_url:
raise RuntimeError("Must initialize proxy_url before requesting proxy_conn")
self._proxy_conn = HTTPConnection(self.proxy_url, adapter=_http_adapter)
return self._proxy_conn
def user_info(self) -> Mapping[str, Any]:
if not self._user_info:
self._user_info = self.api_conn().get_json("ping")
return self._user_info
def global_bg_logger(self) -> "_BackgroundLogger":
return getattr(self._override_bg_logger, "logger", None) or self._global_bg_logger.get()
# Should only be called by the login function.
def login_replace_api_conn(self, api_conn: "HTTPConnection"):
self._global_bg_logger.get().internal_replace_api_conn(api_conn)
def flush(self):
self._global_bg_logger.get().flush()
def enforce_queue_size_limit(self, enforce: bool) -> None:
"""
Set queue size limit enforcement for the global background logger.
"""
bg_logger = self._global_bg_logger.get()
bg_logger.enforce_queue_size_limit(enforce)
def set_masking_function(self, masking_function: Callable[[Any], Any] | None) -> None:
"""Set the masking function on the background logger."""
self.global_bg_logger().set_masking_function(masking_function)
_state: BraintrustState = None # type: ignore
_http_adapter: HTTPAdapter | None = None
def set_http_adapter(adapter: HTTPAdapter) -> None:
"""
Specify a custom HTTP adapter to use for all network requests. This is useful for setting custom retry policies, timeouts, etc.
Braintrust uses the `requests` library, so the adapter should be an instance of `requests.adapters.HTTPAdapter`. Alternatively, consider
sub-classing our `RetryRequestExceptionsAdapter` to get automatic retries on network-related exceptions.
:param adapter: The adapter to use.
"""
global _http_adapter
_http_adapter = adapter
if _state._app_conn:
_state._app_conn._set_adapter(adapter=adapter)
_state._app_conn._reset()
if _state._api_conn:
_state._api_conn._set_adapter(adapter=adapter)
_state._api_conn._reset()
class RetryRequestExceptionsAdapter(HTTPAdapter):
"""An HTTP adapter that automatically retries requests on connection exceptions.
This adapter extends requests' HTTPAdapter to add retry logic for common network-related
exceptions including connection errors, timeouts, and other HTTP errors. It implements
an exponential backoff strategy between retries to avoid overwhelming servers during
intermittent connectivity issues.
Attributes:
base_num_retries: Maximum number of retries before giving up and re-raising the exception.
backoff_factor: A multiplier used to determine the time to wait between retries.
The actual wait time is calculated as: backoff_factor * (2 ** retry_count).
default_timeout_secs: Default timeout in seconds for requests that don't specify one.
Prevents indefinite hangs on stale connections.
"""
def __init__(
self,
*args: Any,
base_num_retries: int = 0,
backoff_factor: float = 0.5,
default_timeout_secs: float = 60,
**kwargs: Any,
):
self.base_num_retries = base_num_retries
self.backoff_factor = backoff_factor
self.default_timeout_secs = default_timeout_secs
super().__init__(*args, **kwargs)
def send(self, *args, **kwargs):
# Apply default timeout if none provided to prevent indefinite hangs
if kwargs.get("timeout") is None:
kwargs["timeout"] = self.default_timeout_secs
num_prev_retries = 0
while True:
try:
response = super().send(*args, **kwargs)
# Fully-download the content to ensure we catch any errors from
# downloading.
if not response.is_redirect and response.content:
pass
return response
except (urllib3.exceptions.HTTPError, requests.exceptions.RequestException) as e:
if num_prev_retries < self.base_num_retries:
if isinstance(e, requests.exceptions.ReadTimeout):
# Clear all connection pools to discard stale connections. This
# fixes hangs caused by NAT gateways silently dropping idle TCP
# connections (e.g., Azure's ~4 min timeout). close() calls
# PoolManager.clear() which is thread-safe: in-flight requests
# keep their checked-out connections, and new requests create
# fresh pools on demand.
self.close()
# Emulates the sleeping logic in the backoff_factor of urllib3 Retry
sleep_s = self.backoff_factor * (2**num_prev_retries)
print("Retrying request after error:", e, file=sys.stderr)
print("Sleeping for", sleep_s, "seconds", file=sys.stderr)
time.sleep(sleep_s)
num_prev_retries += 1
else:
raise e
class HTTPConnection:
def __init__(self, base_url: str, adapter: HTTPAdapter | None = None):
self.base_url = base_url
self.token = None
self.adapter = adapter
self._reset(total=0)
def ping(self) -> bool:
try:
resp = self.get("ping")
return resp.ok
except requests.exceptions.ConnectionError:
return False
def make_long_lived(self) -> None:
if not self.adapter:
timeout_secs = parse_env_var_float("BRAINTRUST_HTTP_TIMEOUT", 60.0)
self.adapter = RetryRequestExceptionsAdapter(
base_num_retries=10, backoff_factor=0.5, default_timeout_secs=timeout_secs
)
self._reset()
@staticmethod
def sanitize_token(token: str) -> str:
return token.rstrip("\n")
def set_token(self, token: str) -> None:
token = HTTPConnection.sanitize_token(token)
self.token = token
self._set_session_token()
def _set_adapter(self, adapter: HTTPAdapter | None) -> None:
self.adapter = adapter
def _reset(self, **retry_kwargs: Any) -> None:
self.session = requests.Session()
adapter = self.adapter
if adapter is None:
retry = Retry(**retry_kwargs)
adapter = HTTPAdapter(max_retries=retry)
self.session.mount("http://", adapter)
self.session.mount("https://", adapter)
self._set_session_token()
def _set_session_token(self) -> None:
if self.token:
self.session.headers.update({"Authorization": f"Bearer {self.token}"})
def get(self, path: str, *args: Any, **kwargs: Any) -> requests.Response:
return self.session.get(_urljoin(self.base_url, path), *args, **kwargs)
def post(self, path: str, *args: Any, **kwargs: Any) -> requests.Response:
return self.session.post(_urljoin(self.base_url, path), *args, **kwargs)
def patch(self, path: str, *args: Any, **kwargs: Any) -> requests.Response:
return self.session.patch(_urljoin(self.base_url, path), *args, **kwargs)
def put(self, path: str, *args: Any, **kwargs: Any) -> requests.Response:
return self.session.put(_urljoin(self.base_url, path), *args, **kwargs)
def delete(self, path: str, *args: Any, **kwargs: Any) -> requests.Response:
return self.session.delete(_urljoin(self.base_url, path), *args, **kwargs)
def get_json(self, object_type: str, args: Mapping[str, Any] | None = None) -> Mapping[str, Any]:
resp = self.get(f"/{object_type}", params=args)
response_raise_for_status(resp)
return resp.json()
def post_json(self, object_type: str, args: Mapping[str, Any] | None = None) -> Any:
resp = self.post(f"/{object_type.lstrip('/')}", json=args)
response_raise_for_status(resp)
return resp.json()
def patch_json(self, object_type: str, args: Mapping[str, Any] | None = None) -> Any:
resp = self.patch(f"/{object_type.lstrip('/')}", json=args)
response_raise_for_status(resp)
return resp.json()
async def aget_json(
self, object_type: str, args: Optional[Mapping[str, Any]] = None, retries: int = 0
) -> Mapping[str, Any] | None:
"""
Async version of get_json. Makes a true async HTTP GET request and returns JSON response.
"""
from importlib.util import find_spec
tries = retries + 1
use_urllib = find_spec("aiohttp") is None
for i in range(tries):
try:
# Build URL using the same logic as sync version
url = _urljoin(self.base_url, f"/{object_type}")
if args:
url += "?" + urlencode(_strip_nones(args))
# check if aiohttp is available, otherwise fall back to asyncio approach
if use_urllib:
# Fall back to asyncio + urllib approach
return await self._make_asyncio_request(url)
return await self._make_aiohttp_request(url)
except Exception as e:
if i < tries - 1:
_logger.warning(f"Retrying async API request {object_type} {args}: {e}")
await asyncio.sleep(0.1 * (i + 1)) # Progressive backoff
continue
raise
# Needed for type checking.
raise Exception("unreachable")
async def _make_aiohttp_request(self, url: str) -> Mapping[str, Any]:
"""Make async HTTP request using aiohttp"""
import aiohttp
headers = {}
if self.token:
headers["Authorization"] = f"Bearer {self.token}"
async with aiohttp.ClientSession() as session:
async with session.get(url, headers=headers) as response:
if response.status >= 400:
error_text = await response.text()
raise Exception(f"HTTP {response.status}: {error_text}")
return await response.json()
async def _make_asyncio_request(self, url: str) -> Mapping[str, Any]:
"""Make async HTTP request using asyncio and urllib (fallback)"""
loop = asyncio.get_running_loop()
timeout_secs = parse_env_var_float("BRAINTRUST_HTTP_TIMEOUT", 60.0)
def sync_request():
request = Request(url)
if self.token:
request.add_header("Authorization", f"Bearer {self.token}")
try:
response_obj = urlopen(request, timeout=timeout_secs)
response_data = response_obj.read()
return json.loads(response_data.decode("utf-8"))
except HTTPError as e:
error_body = e.read().decode("utf-8") if hasattr(e, "read") else str(e)
raise Exception(f"HTTP {e.code}: {error_body}")
except URLError as e:
raise Exception(f"URL Error: {e}")
return await loop.run_in_executor(HTTP_REQUEST_THREAD_POOL, sync_request)
# Sometimes we'd like to launch network requests concurrently. We provide a
# thread pool to accomplish this. Use a multiple of number of CPU cores to limit
# concurrency.
HTTP_REQUEST_THREAD_POOL = concurrent.futures.ThreadPoolExecutor(max_workers=cpu_count())
def api_conn():
return _state.api_conn()
def app_conn():
return _state.app_conn()
def proxy_conn():
return _state.proxy_conn()
def user_info():
return _state.user_info()
def org_id():
return _state.org_id
def construct_json_array(items: Sequence[str]):
return "[" + ",".join(items) + "]"
def construct_logs3_data(items: Sequence[LogItemWithMeta]):
rowsS = construct_json_array([item.str_value for item in items])
return '{"rows": ' + rowsS + ', "api_version": ' + str(DATA_API_VERSION) + "}"
def construct_logs3_overflow_request(key: str, size_bytes: int | None = None) -> dict[str, Any]:
rows: dict[str, Any] = {"type": LOGS3_OVERFLOW_REFERENCE_TYPE, "key": key}
if size_bytes is not None:
rows["size_bytes"] = size_bytes
return {"rows": rows, "api_version": DATA_API_VERSION}
def pick_logs3_overflow_object_ids(row: Mapping[str, Any]) -> dict[str, Any]:
object_ids: dict[str, Any] = {}
for key in OBJECT_ID_KEYS:
if key in row:
object_ids[key] = row[key]
return object_ids
def stringify_with_overflow_meta(item: dict[str, Any]) -> LogItemWithMeta:
str_value = bt_dumps(item)
return LogItemWithMeta(
str_value=str_value,
overflow_meta=Logs3OverflowInputRow(
object_ids=pick_logs3_overflow_object_ids(item),
has_comment="comment" in item,
is_delete=item.get(OBJECT_DELETE_FIELD) is True,
byte_size=utf8_byte_length(str_value),
),
)
def utf8_byte_length(value: str) -> int:
return len(value.encode("utf-8"))
class _MaskingError:
"""Internal class to signal masking errors that need special handling."""
def __init__(self, field_name: str, error_type: str):
self.field_name = field_name
self.error_type = error_type
self.error_msg = f"ERROR: Failed to mask field '{field_name}' - {error_type}"
def _apply_masking_to_field(masking_function: Callable[[Any], Any], data: Any, field_name: str) -> Any:
"""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.
"""
try:
return masking_function(data)
except Exception as mask_error:
# Return a generic error message without the stack trace to avoid leaking PII
error_type = type(mask_error).__name__
# For scores and metrics fields, return a special error object
# to signal the field should be dropped and error logged
if field_name in ["scores", "metrics"]:
return _MaskingError(field_name, error_type)
# For metadata field that expects dict type, return a dict with error key
if field_name == "metadata":
return {"error": f"ERROR: Failed to mask field '{field_name}' - {error_type}"}
# For other fields, return the error message as a string
return f"ERROR: Failed to mask field '{field_name}' - {error_type}"
class _BackgroundLogger(ABC):
@abstractmethod
def log(self, *args: LazyValue[dict[str, Any]]) -> None:
pass
@abstractmethod
def flush(self, batch_size: int | None = None):
pass