Skip to content

Commit b4a5757

Browse files
authored
feat: Add ability to track time to first token for LDAIConfigTracker (#37)
1 parent a3b4025 commit b4a5757

File tree

2 files changed

+31
-0
lines changed

2 files changed

+31
-0
lines changed

ldai/testing/test_tracker.py

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -75,6 +75,21 @@ def test_tracks_duration_of(client: LDClient):
7575
assert calls[0].args[3] == pytest.approx(10, rel=10)
7676

7777

78+
def test_tracks_time_to_first_token(client: LDClient):
79+
context = Context.create('user-key')
80+
tracker = LDAIConfigTracker(client, "variation-key", "config-key", context)
81+
tracker.track_time_to_first_token(100)
82+
83+
client.track.assert_called_with( # type: ignore
84+
'$ld:ai:tokens:ttf',
85+
context,
86+
{'variationKey': 'variation-key', 'configKey': 'config-key'},
87+
100
88+
)
89+
90+
assert tracker.get_summary().time_to_first_token == 100
91+
92+
7893
def test_tracks_duration_of_with_exception(client: LDClient):
7994
context = Context.create('user-key')
8095
tracker = LDAIConfigTracker(client, "variation-key", "config-key", context)

ldai/tracker.py

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -40,6 +40,7 @@ def __init__(self):
4040
self._success = None
4141
self._feedback = None
4242
self._usage = None
43+
self._time_to_first_token = None
4344

4445
@property
4546
def duration(self) -> Optional[int]:
@@ -57,6 +58,10 @@ def feedback(self) -> Optional[Dict[str, FeedbackKind]]:
5758
def usage(self) -> Optional[TokenUsage]:
5859
return self._usage
5960

61+
@property
62+
def time_to_first_token(self) -> Optional[int]:
63+
return self._time_to_first_token
64+
6065

6166
class LDAIConfigTracker:
6267
"""
@@ -102,6 +107,17 @@ def track_duration(self, duration: int) -> None:
102107
'$ld:ai:duration:total', self._context, self.__get_track_data(), duration
103108
)
104109

110+
def track_time_to_first_token(self, time_to_first_token: int) -> None:
111+
"""
112+
Manually track the time to first token of an AI operation.
113+
114+
:param time_to_first_token: Time to first token in milliseconds.
115+
"""
116+
self._summary._time_to_first_token = time_to_first_token
117+
self._ld_client.track(
118+
'$ld:ai:tokens:ttf', self._context, self.__get_track_data(), time_to_first_token
119+
)
120+
105121
def track_duration_of(self, func):
106122
"""
107123
Automatically track the duration of an AI operation.

0 commit comments

Comments
 (0)