openlit 1.33.14__py3-none-any.whl → 1.33.16__py3-none-any.whl

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.
@@ -13,6 +13,8 @@ from openlit.__helpers import (
13
13
  get_image_model_cost,
14
14
  general_tokens,
15
15
  handle_exception,
16
+ extract_and_format_input,
17
+ concatenate_all_contents,
16
18
  response_as_dict,
17
19
  calculate_ttft,
18
20
  calculate_tbt,
@@ -24,6 +26,409 @@ from openlit.semcov import SemanticConvetion
24
26
  # Initialize logger for logging potential issues and operations
25
27
  logger = logging.getLogger(__name__)
26
28
 
29
+ def async_responses(version, environment, application_name,
30
+ tracer, pricing_info, capture_message_content, metrics, disable_metrics):
31
+ """
32
+ Generates a telemetry wrapper for chat completions to collect metrics.
33
+
34
+ Args:
35
+ version: Version of the monitoring package.
36
+ environment: Deployment environment (e.g., production, staging).
37
+ application_name: Name of the application using the OpenAI API.
38
+ tracer: OpenTelemetry tracer for creating spans.
39
+ pricing_info: Information used for calculating the cost of OpenAI usage.
40
+ capture_message_content: Flag indicating whether to trace the actual content.
41
+
42
+ Returns:
43
+ A function that wraps the chat completions method to add telemetry.
44
+ """
45
+
46
+ class TracedAsyncStream:
47
+ """
48
+ Wrapper for streaming responses to collect metrics and trace data.
49
+ Wraps the response to collect message IDs and aggregated response.
50
+
51
+ This class implements the '__aiter__' and '__anext__' methods that
52
+ handle asynchronous streaming responses.
53
+
54
+ This class also implements '__aenter__' and '__aexit__' methods that
55
+ handle asynchronous context management protocol.
56
+ """
57
+ def __init__(
58
+ self,
59
+ wrapped,
60
+ span,
61
+ kwargs,
62
+ server_address,
63
+ server_port,
64
+ **args,
65
+ ):
66
+ self.__wrapped__ = wrapped
67
+ self._span = span
68
+ # Placeholder for aggregating streaming response
69
+ self._llmresponse = ""
70
+ self._response_id = ""
71
+ self._response_model = ""
72
+ self._finish_reason = ""
73
+ self._input_tokens = ""
74
+ self._output_tokens = ""
75
+
76
+ self._args = args
77
+ self._kwargs = kwargs
78
+ self._start_time = time.time()
79
+ self._end_time = None
80
+ self._timestamps = []
81
+ self._ttft = 0
82
+ self._tbt = 0
83
+ self._server_address = server_address
84
+ self._server_port = server_port
85
+
86
+ async def __aenter__(self):
87
+ await self.__wrapped__.__aenter__()
88
+ return self
89
+
90
+ async def __aexit__(self, exc_type, exc_value, traceback):
91
+ await self.__wrapped__.__aexit__(exc_type, exc_value, traceback)
92
+
93
+ def __aiter__(self):
94
+ return self
95
+
96
+ async def __getattr__(self, name):
97
+ """Delegate attribute access to the wrapped object."""
98
+ return getattr(await self.__wrapped__, name)
99
+
100
+ async def __anext__(self):
101
+ try:
102
+ chunk = await self.__wrapped__.__anext__()
103
+ end_time = time.time()
104
+ # Record the timestamp for the current chunk
105
+ self._timestamps.append(end_time)
106
+
107
+ if len(self._timestamps) == 1:
108
+ # Calculate time to first chunk
109
+ self._ttft = calculate_ttft(self._timestamps, self._start_time)
110
+
111
+ chunked = response_as_dict(chunk)
112
+ # Collect message IDs and aggregated response from events
113
+ if chunked.get('type') == "response.output_text.delta":
114
+ self._llmresponse += chunked.get('delta')
115
+ if chunked.get('type') == "response.completed":
116
+ self._response_id = chunked.get('response').get('id')
117
+ self._response_model = chunked.get('response').get('model')
118
+ self._finish_reason = chunked.get('response').get('status')
119
+ self._input_tokens = chunked.get('response').get('usage').get('input_tokens')
120
+ self._output_tokens = chunked.get('response').get('usage').get('output_tokens')
121
+ return chunk
122
+ except StopAsyncIteration:
123
+ # Handling exception ensure observability without disrupting operation
124
+ try:
125
+ self._end_time = time.time()
126
+ if len(self._timestamps) > 1:
127
+ self._tbt = calculate_tbt(self._timestamps)
128
+
129
+ try:
130
+ formatted_messages = extract_and_format_input(self._kwargs.get('input', ''))
131
+ prompt = concatenate_all_contents(formatted_messages)
132
+ except:
133
+ prompt = self._kwargs.get('input', '')
134
+
135
+ request_model = self._kwargs.get("model", "gpt-4o")
136
+
137
+ # Calculate cost of the operation
138
+ cost = get_chat_model_cost(request_model,
139
+ pricing_info, self._input_tokens,
140
+ self._output_tokens)
141
+
142
+ # Set Span attributes (OTel Semconv)
143
+ self._span.set_attribute(TELEMETRY_SDK_NAME, "openlit")
144
+ self._span.set_attribute(SemanticConvetion.GEN_AI_OPERATION,
145
+ SemanticConvetion.GEN_AI_OPERATION_TYPE_CHAT)
146
+ self._span.set_attribute(SemanticConvetion.GEN_AI_SYSTEM,
147
+ SemanticConvetion.GEN_AI_SYSTEM_OPENAI)
148
+ self._span.set_attribute(SemanticConvetion.GEN_AI_REQUEST_MODEL,
149
+ request_model)
150
+ self._span.set_attribute(SemanticConvetion.GEN_AI_REQUEST_SEED,
151
+ self._kwargs.get("seed", ""))
152
+ self._span.set_attribute(SemanticConvetion.SERVER_PORT,
153
+ self._server_port)
154
+ self._span.set_attribute(SemanticConvetion.GEN_AI_REQUEST_MAX_TOKENS,
155
+ self._kwargs.get("max_output_tokens", -1))
156
+ self._span.set_attribute(SemanticConvetion.GEN_AI_REQUEST_STOP_SEQUENCES,
157
+ self._kwargs.get("stop", []))
158
+ self._span.set_attribute(SemanticConvetion.GEN_AI_REQUEST_TEMPERATURE,
159
+ self._kwargs.get("temperature", 1.0))
160
+ self._span.set_attribute(SemanticConvetion.GEN_AI_REQUEST_TOP_P,
161
+ self._kwargs.get("top_p", 1.0))
162
+ self._span.set_attribute(SemanticConvetion.GEN_AI_RESPONSE_FINISH_REASON,
163
+ [self._finish_reason])
164
+ self._span.set_attribute(SemanticConvetion.GEN_AI_RESPONSE_ID,
165
+ self._response_id)
166
+ self._span.set_attribute(SemanticConvetion.GEN_AI_RESPONSE_MODEL,
167
+ self._response_model)
168
+ self._span.set_attribute(SemanticConvetion.GEN_AI_USAGE_INPUT_TOKENS,
169
+ self._input_tokens)
170
+ self._span.set_attribute(SemanticConvetion.GEN_AI_USAGE_OUTPUT_TOKENS,
171
+ self._output_tokens)
172
+ self._span.set_attribute(SemanticConvetion.SERVER_ADDRESS,
173
+ self._server_address)
174
+ if isinstance(self._llmresponse, str):
175
+ self._span.set_attribute(SemanticConvetion.GEN_AI_OUTPUT_TYPE,
176
+ "text")
177
+ else:
178
+ self._span.set_attribute(SemanticConvetion.GEN_AI_OUTPUT_TYPE,
179
+ "json")
180
+
181
+ # Set Span attributes (Extra)
182
+ self._span.set_attribute(DEPLOYMENT_ENVIRONMENT,
183
+ environment)
184
+ self._span.set_attribute(SERVICE_NAME,
185
+ application_name)
186
+ self._span.set_attribute(SemanticConvetion.GEN_AI_REQUEST_USER,
187
+ self._kwargs.get("user", ""))
188
+ self._span.set_attribute(SemanticConvetion.GEN_AI_REQUEST_IS_STREAM,
189
+ True)
190
+ self._span.set_attribute(SemanticConvetion.GEN_AI_USAGE_TOTAL_TOKENS,
191
+ self._input_tokens + self._output_tokens)
192
+ self._span.set_attribute(SemanticConvetion.GEN_AI_USAGE_COST,
193
+ cost)
194
+ self._span.set_attribute(SemanticConvetion.GEN_AI_SERVER_TBT,
195
+ self._tbt)
196
+ self._span.set_attribute(SemanticConvetion.GEN_AI_SERVER_TTFT,
197
+ self._ttft)
198
+ self._span.set_attribute(SemanticConvetion.GEN_AI_SDK_VERSION,
199
+ version)
200
+
201
+ if capture_message_content:
202
+ self._span.add_event(
203
+ name=SemanticConvetion.GEN_AI_CONTENT_PROMPT_EVENT,
204
+ attributes={
205
+ SemanticConvetion.GEN_AI_CONTENT_PROMPT: prompt,
206
+ },
207
+ )
208
+ self._span.add_event(
209
+ name=SemanticConvetion.GEN_AI_CONTENT_COMPLETION_EVENT,
210
+ attributes={
211
+ SemanticConvetion.GEN_AI_CONTENT_COMPLETION: self._llmresponse,
212
+ },
213
+ )
214
+ self._span.set_status(Status(StatusCode.OK))
215
+
216
+ if disable_metrics is False:
217
+ attributes = create_metrics_attributes(
218
+ service_name=application_name,
219
+ deployment_environment=environment,
220
+ operation=SemanticConvetion.GEN_AI_OPERATION_TYPE_CHAT,
221
+ system=SemanticConvetion.GEN_AI_SYSTEM_OPENAI,
222
+ request_model=request_model,
223
+ server_address=self._server_address,
224
+ server_port=self._server_port,
225
+ response_model=self._response_model,
226
+ )
227
+
228
+ metrics["genai_client_usage_tokens"].record(
229
+ self._input_tokens + self._output_tokens, attributes
230
+ )
231
+ metrics["genai_client_operation_duration"].record(
232
+ self._end_time - self._start_time, attributes
233
+ )
234
+ metrics["genai_server_tbt"].record(
235
+ self._tbt, attributes
236
+ )
237
+ metrics["genai_server_ttft"].record(
238
+ self._ttft, attributes
239
+ )
240
+ metrics["genai_requests"].add(1, attributes)
241
+ metrics["genai_completion_tokens"].add(self._output_tokens, attributes)
242
+ metrics["genai_prompt_tokens"].add(self._input_tokens, attributes)
243
+ metrics["genai_cost"].record(cost, attributes)
244
+
245
+ except Exception as e:
246
+ handle_exception(self._span, e)
247
+ logger.error("Error in trace creation: %s", e)
248
+ finally:
249
+ self._span.end()
250
+ raise
251
+
252
+ async def wrapper(wrapped, instance, args, kwargs):
253
+ """
254
+ Wraps the 'chat.completions' API call to add telemetry.
255
+
256
+ This collects metrics such as execution time, cost, and token usage, and handles errors
257
+ gracefully, adding details to the trace for observability.
258
+
259
+ Args:
260
+ wrapped: The original 'chat.completions' method to be wrapped.
261
+ instance: The instance of the class where the original method is defined.
262
+ args: Positional arguments for the 'chat.completions' method.
263
+ kwargs: Keyword arguments for the 'chat.completions' method.
264
+
265
+ Returns:
266
+ The response from the original 'chat.completions' method.
267
+ """
268
+
269
+ # Check if streaming is enabled for the API call
270
+ streaming = kwargs.get("stream", False)
271
+ server_address, server_port = set_server_address_and_port(instance, "api.openai.com", 443)
272
+ request_model = kwargs.get("model", "gpt-4o")
273
+
274
+ span_name = f"{SemanticConvetion.GEN_AI_OPERATION_TYPE_CHAT} {request_model}"
275
+
276
+ # pylint: disable=no-else-return
277
+ if streaming:
278
+ # Special handling for streaming response to accommodate the nature of data flow
279
+ awaited_wrapped = await wrapped(*args, **kwargs)
280
+ span = tracer.start_span(span_name, kind=SpanKind.CLIENT)
281
+
282
+ return TracedAsyncStream(awaited_wrapped, span, kwargs, server_address, server_port)
283
+
284
+ # Handling for non-streaming responses
285
+ else:
286
+ with tracer.start_as_current_span(span_name, kind= SpanKind.CLIENT) as span:
287
+ start_time = time.time()
288
+ response = await wrapped(*args, **kwargs)
289
+ end_time = time.time()
290
+
291
+ response_dict = response_as_dict(response)
292
+
293
+ try:
294
+ try:
295
+ formatted_messages = extract_and_format_input(kwargs.get('input', ''))
296
+ prompt = concatenate_all_contents(formatted_messages)
297
+ except:
298
+ prompt = kwargs.get('input', '')
299
+
300
+ input_tokens = response_dict.get('usage').get('input_tokens')
301
+ output_tokens = response_dict.get('usage').get('output_tokens')
302
+
303
+ # Calculate cost of the operation
304
+ cost = get_chat_model_cost(request_model,
305
+ pricing_info, input_tokens,
306
+ output_tokens)
307
+
308
+ # Set base span attribues (OTel Semconv)
309
+ span.set_attribute(TELEMETRY_SDK_NAME, "openlit")
310
+ span.set_attribute(SemanticConvetion.GEN_AI_OPERATION,
311
+ SemanticConvetion.GEN_AI_OPERATION_TYPE_CHAT)
312
+ span.set_attribute(SemanticConvetion.GEN_AI_SYSTEM,
313
+ SemanticConvetion.GEN_AI_SYSTEM_OPENAI)
314
+ span.set_attribute(SemanticConvetion.GEN_AI_REQUEST_MODEL,
315
+ request_model)
316
+ span.set_attribute(SemanticConvetion.GEN_AI_REQUEST_SEED,
317
+ kwargs.get("seed", ""))
318
+ span.set_attribute(SemanticConvetion.SERVER_PORT,
319
+ server_port)
320
+ span.set_attribute(SemanticConvetion.GEN_AI_REQUEST_MAX_TOKENS,
321
+ kwargs.get("max_output_tokens", -1))
322
+ span.set_attribute(SemanticConvetion.GEN_AI_REQUEST_STOP_SEQUENCES,
323
+ kwargs.get("stop", []))
324
+ span.set_attribute(SemanticConvetion.GEN_AI_REQUEST_TEMPERATURE,
325
+ str(response_dict.get("temperature", 1.0)))
326
+ span.set_attribute(SemanticConvetion.GEN_AI_REQUEST_TOP_P,
327
+ str(response_dict.get("top_p", 1.0)))
328
+ span.set_attribute(SemanticConvetion.GEN_AI_RESPONSE_ID,
329
+ response_dict.get("id"))
330
+ span.set_attribute(SemanticConvetion.GEN_AI_RESPONSE_MODEL,
331
+ response_dict.get('model'))
332
+ span.set_attribute(SemanticConvetion.GEN_AI_USAGE_INPUT_TOKENS,
333
+ input_tokens)
334
+ span.set_attribute(SemanticConvetion.GEN_AI_USAGE_OUTPUT_TOKENS,
335
+ output_tokens)
336
+ span.set_attribute(SemanticConvetion.SERVER_ADDRESS,
337
+ server_address)
338
+
339
+ # Set base span attribues (Extras)
340
+ span.set_attribute(DEPLOYMENT_ENVIRONMENT,
341
+ environment)
342
+ span.set_attribute(SERVICE_NAME,
343
+ application_name)
344
+ span.set_attribute(SemanticConvetion.GEN_AI_REQUEST_USER,
345
+ kwargs.get("user", ""))
346
+ span.set_attribute(SemanticConvetion.GEN_AI_REQUEST_IS_STREAM,
347
+ False)
348
+ span.set_attribute(SemanticConvetion.GEN_AI_USAGE_TOTAL_TOKENS,
349
+ input_tokens + output_tokens)
350
+ span.set_attribute(SemanticConvetion.GEN_AI_USAGE_COST,
351
+ cost)
352
+ span.set_attribute(SemanticConvetion.GEN_AI_SERVER_TTFT,
353
+ end_time - start_time)
354
+ span.set_attribute(SemanticConvetion.GEN_AI_SDK_VERSION,
355
+ version)
356
+
357
+ if capture_message_content:
358
+ span.add_event(
359
+ name=SemanticConvetion.GEN_AI_CONTENT_PROMPT_EVENT,
360
+ attributes={
361
+ SemanticConvetion.GEN_AI_CONTENT_PROMPT: prompt,
362
+ },
363
+ )
364
+
365
+ for i in range(kwargs.get('n',1)):
366
+ span.set_attribute(SemanticConvetion.GEN_AI_RESPONSE_FINISH_REASON,
367
+ [response_dict.get('status')])
368
+ try:
369
+ llm_response = str(response_dict.get('output')[i].get('content')[0].get('text',''))
370
+ except:
371
+ llm_response = ''
372
+
373
+ if capture_message_content:
374
+ span.add_event(
375
+ name=SemanticConvetion.GEN_AI_CONTENT_COMPLETION_EVENT,
376
+ attributes={
377
+ # pylint: disable=line-too-long
378
+ SemanticConvetion.GEN_AI_CONTENT_COMPLETION: llm_response,
379
+ },
380
+ )
381
+ if kwargs.get('tools'):
382
+ span.set_attribute(SemanticConvetion.GEN_AI_TOOL_CALLS,
383
+ str(response_dict.get('tools')))
384
+
385
+ if isinstance(llm_response, str):
386
+ span.set_attribute(SemanticConvetion.GEN_AI_OUTPUT_TYPE,
387
+ "text")
388
+ elif llm_response is not None:
389
+ span.set_attribute(SemanticConvetion.GEN_AI_OUTPUT_TYPE,
390
+ "json")
391
+
392
+ span.set_status(Status(StatusCode.OK))
393
+
394
+ if disable_metrics is False:
395
+ attributes = create_metrics_attributes(
396
+ service_name=application_name,
397
+ deployment_environment=environment,
398
+ operation=SemanticConvetion.GEN_AI_OPERATION_TYPE_CHAT,
399
+ system=SemanticConvetion.GEN_AI_SYSTEM_OPENAI,
400
+ request_model=request_model,
401
+ server_address=server_address,
402
+ server_port=server_port,
403
+ response_model=response_dict.get('model'),
404
+ )
405
+
406
+ metrics["genai_client_usage_tokens"].record(
407
+ input_tokens + output_tokens, attributes
408
+ )
409
+ metrics["genai_client_operation_duration"].record(
410
+ end_time - start_time, attributes
411
+ )
412
+ metrics["genai_server_ttft"].record(
413
+ end_time - start_time, attributes
414
+ )
415
+ metrics["genai_requests"].add(1, attributes)
416
+ metrics["genai_completion_tokens"].add(output_tokens, attributes)
417
+ metrics["genai_prompt_tokens"].add(input_tokens, attributes)
418
+ metrics["genai_cost"].record(cost, attributes)
419
+
420
+ # Return original response
421
+ return response
422
+
423
+ except Exception as e:
424
+ handle_exception(span, e)
425
+ logger.error("Error in trace creation: %s", e)
426
+
427
+ # Return original response
428
+ return response
429
+
430
+ return wrapper
431
+
27
432
  def async_chat_completions(version, environment, application_name,
28
433
  tracer, pricing_info, capture_message_content, metrics, disable_metrics):
29
434
  """