-
Notifications
You must be signed in to change notification settings - Fork 261
Expand file tree
/
Copy pathingestion_consumer.py
More file actions
295 lines (246 loc) · 9.44 KB
/
ingestion_consumer.py
File metadata and controls
295 lines (246 loc) · 9.44 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
import json
import logging
import os
import threading
import time
from queue import Empty, Queue
from typing import Any, List, Optional
import backoff
try:
import pydantic.v1 as pydantic
except ImportError:
import pydantic
from langfuse.parse_error import handle_exception
from langfuse.request import APIError, LangfuseClient
from langfuse.Sampler import Sampler
from langfuse.serializer import EventSerializer
from langfuse.types import MaskFunction
from .media_manager import MediaManager
MAX_EVENT_SIZE_BYTES = int(os.environ.get("LANGFUSE_MAX_EVENT_SIZE_BYTES", 1_000_000))
MAX_BATCH_SIZE_BYTES = int(os.environ.get("LANGFUSE_MAX_BATCH_SIZE_BYTES", 2_500_000))
class IngestionMetadata(pydantic.BaseModel):
batch_size: int
sdk_integration: str
sdk_name: str
sdk_version: str
public_key: str
class IngestionConsumer(threading.Thread):
_log = logging.getLogger("langfuse")
_ingestion_queue: Queue
_identifier: int
_client: LangfuseClient
_flush_at: int
_flush_interval: float
_max_retries: int
_public_key: str
_sdk_name: str
_sdk_version: str
_sdk_integration: str
_mask: Optional[MaskFunction]
_sampler: Sampler
_media_manager: MediaManager
def __init__(
self,
*,
ingestion_queue: Queue,
identifier: int,
client: LangfuseClient,
flush_at: int,
flush_interval: float,
max_retries: int,
public_key: str,
media_manager: MediaManager,
sdk_name: str,
sdk_version: str,
sdk_integration: str,
sample_rate: float,
mask: Optional[MaskFunction] = None,
):
"""Create a consumer thread."""
super().__init__()
# It's important to set running in the constructor: if we are asked to
# pause immediately after construction, we might set running to True in
# run() *after* we set it to False in pause... and keep running
# forever.
self.running = True
# Make consumer a daemon thread so that it doesn't block program exit
self.daemon = True
self._ingestion_queue = ingestion_queue
self._identifier = identifier
self._client = client
self._flush_at = flush_at
self._flush_interval = flush_interval
self._max_retries = max_retries
self._public_key = public_key
self._sdk_name = sdk_name
self._sdk_version = sdk_version
self._sdk_integration = sdk_integration
self._mask = mask
self._sampler = Sampler(sample_rate)
self._media_manager = media_manager
def _next(self):
"""Return the next batch of items to upload."""
events = []
start_time = time.monotonic()
total_size = 0
while len(events) < self._flush_at:
elapsed = time.monotonic() - start_time
if elapsed >= self._flush_interval:
break
try:
event = self._ingestion_queue.get(
block=True, timeout=self._flush_interval - elapsed
)
# convert pydantic models to dicts
if "body" in event and isinstance(event["body"], pydantic.BaseModel):
event["body"] = event["body"].dict(exclude_none=True)
# sample event
if not self._sampler.sample_event(event):
self._ingestion_queue.task_done()
continue
# apply mask
self._apply_mask_in_place(event)
# handle multimodal data
self._media_manager.process_media_in_event(event)
# truncate item if it exceeds size limit
item_size = self._truncate_item_in_place(
event=event,
max_size=MAX_EVENT_SIZE_BYTES,
log_message="<truncated due to size exceeding limit>",
)
# check for serialization errors
try:
json.dumps(event, cls=EventSerializer)
except Exception as e:
self._log.error(f"Error serializing item, skipping: {e}")
self._ingestion_queue.task_done()
continue
events.append(event)
total_size += item_size
if total_size >= MAX_BATCH_SIZE_BYTES:
self._log.debug("hit batch size limit (size: %d)", total_size)
break
except Empty:
break
except Exception as e:
self._log.warning(
"Failed to process event in IngestionConsumer, skipping",
exc_info=e,
)
self._ingestion_queue.task_done()
self._log.debug(
"~%d items in the Langfuse queue", self._ingestion_queue.qsize()
)
return events
def _truncate_item_in_place(
self,
*,
event: Any,
max_size: int,
log_message: Optional[str] = None,
) -> int:
"""Truncate the item in place to fit within the size limit."""
item_size = self._get_item_size(event)
self._log.debug(f"item size {item_size}")
if item_size > max_size:
self._log.warning(
"Item exceeds size limit (size: %s), dropping input / output / metadata of item until it fits.",
item_size,
)
if "body" in event:
drop_candidates = ["input", "output", "metadata"]
sorted_field_sizes = sorted(
[
(
field,
self._get_item_size((event["body"][field]))
if field in event["body"]
else 0,
)
for field in drop_candidates
],
key=lambda x: x[1],
)
# drop the largest field until the item size is within the limit
for _ in range(len(sorted_field_sizes)):
field_to_drop, size_to_drop = sorted_field_sizes.pop()
if field_to_drop not in event["body"]:
continue
event["body"][field_to_drop] = log_message
item_size -= size_to_drop
self._log.debug(
f"Dropped field {field_to_drop}, new item size {item_size}"
)
if item_size <= max_size:
break
# if item does not have body or input/output fields, drop the event
if "body" not in event or (
"input" not in event["body"] and "output" not in event["body"]
):
self._log.warning(
"Item does not have body or input/output fields, dropping item."
)
self._ingestion_queue.task_done()
return 0
return self._get_item_size(event)
def _get_item_size(self, item: Any) -> int:
"""Return the size of the item in bytes."""
return len(json.dumps(item, cls=EventSerializer).encode())
def _apply_mask_in_place(self, event: dict):
"""Apply the mask function to the event. This is done in place."""
if not self._mask:
return
body = event["body"] if "body" in event else {}
for key in ("input", "output"):
if key in body:
try:
body[key] = self._mask(data=body[key])
except Exception as e:
self._log.error(f"Mask function failed with error: {e}")
body[key] = "<fully masked due to failed mask function>"
def run(self):
"""Run the consumer."""
self._log.debug("consumer is running...")
while self.running:
self.upload()
def upload(self):
"""Upload the next batch of items, return whether successful."""
batch = self._next()
if len(batch) == 0:
return
try:
self._upload_batch(batch)
except Exception as e:
handle_exception(e)
finally:
# mark items as acknowledged from queue
for _ in batch:
self._ingestion_queue.task_done()
def pause(self):
"""Pause the consumer."""
self.running = False
def _upload_batch(self, batch: List[Any]):
self._log.debug("uploading batch of %d items", len(batch))
metadata = IngestionMetadata(
batch_size=len(batch),
sdk_integration=self._sdk_integration,
sdk_name=self._sdk_name,
sdk_version=self._sdk_version,
public_key=self._public_key,
).dict()
@backoff.on_exception(
backoff.expo, Exception, max_tries=self._max_retries, logger=None
)
def execute_task_with_backoff(batch: List[Any]):
try:
self._client.batch_post(batch=batch, metadata=metadata)
except Exception as e:
if (
isinstance(e, APIError)
and 400 <= int(e.status) < 500
and int(e.status) != 429 # retry if rate-limited
):
return
raise e
execute_task_with_backoff(batch)
self._log.debug("successfully uploaded batch of %d events", len(batch))