openlit 1.32.2__py3-none-any.whl → 1.32.4__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.
@@ -0,0 +1,604 @@
1
+ # pylint: disable=duplicate-code, broad-exception-caught, too-many-statements, unused-argument, too-many-branches, too-many-instance-attributes, inconsistent-return-statements
2
+ """
3
+ Module for monitoring AI21 calls.
4
+ """
5
+
6
+ import logging
7
+ from opentelemetry.trace import SpanKind, Status, StatusCode
8
+ from opentelemetry.sdk.resources import TELEMETRY_SDK_NAME
9
+ from openlit.__helpers import (
10
+ get_chat_model_cost,
11
+ handle_exception,
12
+ response_as_dict,
13
+ general_tokens
14
+ )
15
+ from openlit.semcov import SemanticConvetion
16
+
17
+ # Initialize logger for logging potential issues and operations
18
+ logger = logging.getLogger(__name__)
19
+
20
+ def chat(gen_ai_endpoint, version, environment, application_name,
21
+ tracer, pricing_info, trace_content, metrics, disable_metrics):
22
+ """
23
+ Generates a telemetry wrapper for chat completions to collect metrics.
24
+
25
+ Args:
26
+ gen_ai_endpoint: Endpoint identifier for logging and tracing.
27
+ version: Version of the monitoring package.
28
+ environment: Deployment environment (e.g., production, staging).
29
+ application_name: Name of the application using the AI21 SDK.
30
+ tracer: OpenTelemetry tracer for creating spans.
31
+ pricing_info: Information used for calculating the cost of AI21 usage.
32
+ trace_content: Flag indicating whether to trace the actual content.
33
+
34
+ Returns:
35
+ A function that wraps the chat completions method to add telemetry.
36
+ """
37
+
38
+ class TracedSyncStream:
39
+ """
40
+ Wrapper for streaming responses to collect metrics and trace data.
41
+
42
+ This class implements the '__aiter__' and '__anext__' methods that
43
+ handle asynchronous streaming responses.
44
+
45
+ This class also implements '__aenter__' and '__aexit__' methods that
46
+ handle asynchronous context management protocol.
47
+ """
48
+ def __init__(
49
+ self,
50
+ wrapped,
51
+ span,
52
+ kwargs,
53
+ **args,
54
+ ):
55
+ self.__wrapped__ = wrapped
56
+ self._span = span
57
+ # Placeholder for aggregating streaming response
58
+ self._llmresponse = ""
59
+ self._response_id = ""
60
+ self._prompt_tokens = 0
61
+ self._completion_tokens = 0
62
+
63
+ self._args = args
64
+ self._kwargs = kwargs
65
+
66
+ def __enter__(self):
67
+ self.__wrapped__.__enter__()
68
+ return self
69
+
70
+ def __exit__(self, exc_type, exc_value, traceback):
71
+ self.__wrapped__.__exit__(exc_type, exc_value, traceback)
72
+
73
+ def __iter__(self):
74
+ return self
75
+
76
+ def __getattr__(self, name):
77
+ """Delegate attribute access to the wrapped object."""
78
+ return getattr(self.__wrapped__, name)
79
+
80
+ def __next__(self):
81
+ try:
82
+ chunk = self.__wrapped__.__next__()
83
+ chunked = response_as_dict(chunk)
84
+ # Collect message IDs and aggregated response from events
85
+ if (len(chunked.get('choices')) > 0 and ('delta' in chunked.get('choices')[0] and
86
+ 'content' in chunked.get('choices')[0].get('delta'))):
87
+
88
+ content = chunked.get('choices')[0].get('delta').get('content')
89
+ if content:
90
+ self._llmresponse += content
91
+
92
+ if chunked.get('usage'):
93
+ self._prompt_tokens = chunked.get('usage').get("prompt_tokens")
94
+ self._completion_tokens = chunked.get('usage').get("completion_tokens")
95
+
96
+ self._response_id = chunked.get('id')
97
+ return chunk
98
+ except StopIteration:
99
+ # Handling exception ensure observability without disrupting operation
100
+ try:
101
+ # Format 'messages' into a single string
102
+ message_prompt = self._kwargs.get("messages", "")
103
+ formatted_messages = []
104
+ for message in message_prompt:
105
+ role = message.role
106
+ content = message.content
107
+
108
+ if isinstance(content, list):
109
+ content_str = ", ".join(
110
+ # pylint: disable=line-too-long
111
+ f'{item["type"]}: {item["text"] if "text" in item else item["image_url"]}'
112
+ if "type" in item else f'text: {item["text"]}'
113
+ for item in content
114
+ )
115
+ formatted_messages.append(f"{role}: {content_str}")
116
+ else:
117
+ formatted_messages.append(f"{role}: {content}")
118
+ prompt = "\n".join(formatted_messages)
119
+
120
+ # Calculate cost of the operation
121
+ cost = get_chat_model_cost(self._kwargs.get("model", "jamba-1.5-mini"),
122
+ pricing_info, self._prompt_tokens,
123
+ self._completion_tokens)
124
+
125
+ # Set Span attributes
126
+ self._span.set_attribute(TELEMETRY_SDK_NAME, "openlit")
127
+ self._span.set_attribute(SemanticConvetion.GEN_AI_SYSTEM,
128
+ SemanticConvetion.GEN_AI_SYSTEM_AI21)
129
+ self._span.set_attribute(SemanticConvetion.GEN_AI_TYPE,
130
+ SemanticConvetion.GEN_AI_TYPE_CHAT)
131
+ self._span.set_attribute(SemanticConvetion.GEN_AI_ENDPOINT,
132
+ gen_ai_endpoint)
133
+ self._span.set_attribute(SemanticConvetion.GEN_AI_RESPONSE_ID,
134
+ self._response_id)
135
+ self._span.set_attribute(SemanticConvetion.GEN_AI_ENVIRONMENT,
136
+ environment)
137
+ self._span.set_attribute(SemanticConvetion.GEN_AI_APPLICATION_NAME,
138
+ application_name)
139
+ self._span.set_attribute(SemanticConvetion.GEN_AI_REQUEST_MODEL,
140
+ self._kwargs.get("model", "jamba-1.5-mini"))
141
+ self._span.set_attribute(SemanticConvetion.GEN_AI_REQUEST_TOP_P,
142
+ self._kwargs.get("top_p", 1.0))
143
+ self._span.set_attribute(SemanticConvetion.GEN_AI_REQUEST_MAX_TOKENS,
144
+ self._kwargs.get("max_tokens", -1))
145
+ self._span.set_attribute(SemanticConvetion.GEN_AI_REQUEST_TEMPERATURE,
146
+ self._kwargs.get("temperature", 1.0))
147
+ self._span.set_attribute(SemanticConvetion.GEN_AI_REQUEST_IS_STREAM,
148
+ True)
149
+ self._span.set_attribute(SemanticConvetion.GEN_AI_USAGE_PROMPT_TOKENS,
150
+ self._prompt_tokens)
151
+ self._span.set_attribute(SemanticConvetion.GEN_AI_USAGE_COMPLETION_TOKENS,
152
+ self._completion_tokens)
153
+ self._span.set_attribute(SemanticConvetion.GEN_AI_USAGE_TOTAL_TOKENS,
154
+ self._prompt_tokens + self._completion_tokens)
155
+ self._span.set_attribute(SemanticConvetion.GEN_AI_USAGE_COST,
156
+ cost)
157
+ if trace_content:
158
+ self._span.add_event(
159
+ name=SemanticConvetion.GEN_AI_CONTENT_PROMPT_EVENT,
160
+ attributes={
161
+ SemanticConvetion.GEN_AI_CONTENT_PROMPT: prompt,
162
+ },
163
+ )
164
+ self._span.add_event(
165
+ name=SemanticConvetion.GEN_AI_CONTENT_COMPLETION_EVENT,
166
+ attributes={
167
+ SemanticConvetion.GEN_AI_CONTENT_COMPLETION: self._llmresponse,
168
+ },
169
+ )
170
+
171
+ self._span.set_status(Status(StatusCode.OK))
172
+
173
+ if disable_metrics is False:
174
+ attributes = {
175
+ TELEMETRY_SDK_NAME:
176
+ "openlit",
177
+ SemanticConvetion.GEN_AI_APPLICATION_NAME:
178
+ application_name,
179
+ SemanticConvetion.GEN_AI_SYSTEM:
180
+ SemanticConvetion.GEN_AI_SYSTEM_AI21,
181
+ SemanticConvetion.GEN_AI_ENVIRONMENT:
182
+ environment,
183
+ SemanticConvetion.GEN_AI_TYPE:
184
+ SemanticConvetion.GEN_AI_TYPE_CHAT,
185
+ SemanticConvetion.GEN_AI_REQUEST_MODEL:
186
+ self._kwargs.get("model", "jamba-1.5-mini")
187
+ }
188
+
189
+ metrics["genai_requests"].add(1, attributes)
190
+ metrics["genai_total_tokens"].add(
191
+ self._prompt_tokens + self._completion_tokens, attributes
192
+ )
193
+ metrics["genai_completion_tokens"].add(self._completion_tokens, attributes)
194
+ metrics["genai_prompt_tokens"].add(self._prompt_tokens, attributes)
195
+ metrics["genai_cost"].record(cost, attributes)
196
+
197
+ except Exception as e:
198
+ handle_exception(self._span, e)
199
+ logger.error("Error in trace creation: %s", e)
200
+ finally:
201
+ self._span.end()
202
+ raise
203
+
204
+ def wrapper(wrapped, instance, args, kwargs):
205
+ """
206
+ Wraps the 'chat.completions' API call to add telemetry.
207
+
208
+ This collects metrics such as execution time, cost, and token usage, and handles errors
209
+ gracefully, adding details to the trace for observability.
210
+
211
+ Args:
212
+ wrapped: The original 'chat.completions' method to be wrapped.
213
+ instance: The instance of the class where the original method is defined.
214
+ args: Positional arguments for the 'chat.completions' method.
215
+ kwargs: Keyword arguments for the 'chat.completions' method.
216
+
217
+ Returns:
218
+ The response from the original 'chat.completions' method.
219
+ """
220
+
221
+ # Check if streaming is enabled for the API call
222
+ streaming = kwargs.get("stream", False)
223
+
224
+ # pylint: disable=no-else-return
225
+ if streaming:
226
+ # Special handling for streaming response to accommodate the nature of data flow
227
+ awaited_wrapped = wrapped(*args, **kwargs)
228
+ span = tracer.start_span(gen_ai_endpoint, kind=SpanKind.CLIENT)
229
+
230
+ return TracedSyncStream(awaited_wrapped, span, kwargs)
231
+
232
+ # Handling for non-streaming responses
233
+ else:
234
+ # pylint: disable=line-too-long
235
+ with tracer.start_as_current_span(gen_ai_endpoint, kind= SpanKind.CLIENT) as span:
236
+ response = wrapped(*args, **kwargs)
237
+
238
+ response_dict = response_as_dict(response)
239
+
240
+ try:
241
+ # Format 'messages' into a single string
242
+ message_prompt = kwargs.get("messages", "")
243
+ formatted_messages = []
244
+ for message in message_prompt:
245
+ role = message.role
246
+ content = message.content
247
+
248
+ if isinstance(content, list):
249
+ content_str = ", ".join(
250
+ # pylint: disable=line-too-long
251
+ f'{item["type"]}: {item["text"] if "text" in item else item["image_url"]}'
252
+ if "type" in item else f'text: {item["text"]}'
253
+ for item in content
254
+ )
255
+ formatted_messages.append(f"{role}: {content_str}")
256
+ else:
257
+ formatted_messages.append(f"{role}: {content}")
258
+ prompt = "\n".join(formatted_messages)
259
+
260
+ # Set base span attribues
261
+ span.set_attribute(TELEMETRY_SDK_NAME, "openlit")
262
+ span.set_attribute(SemanticConvetion.GEN_AI_SYSTEM,
263
+ SemanticConvetion.GEN_AI_SYSTEM_AI21)
264
+ span.set_attribute(SemanticConvetion.GEN_AI_TYPE,
265
+ SemanticConvetion.GEN_AI_TYPE_CHAT)
266
+ span.set_attribute(SemanticConvetion.GEN_AI_ENDPOINT,
267
+ gen_ai_endpoint)
268
+ span.set_attribute(SemanticConvetion.GEN_AI_RESPONSE_ID,
269
+ response_dict.get("id"))
270
+ span.set_attribute(SemanticConvetion.GEN_AI_ENVIRONMENT,
271
+ environment)
272
+ span.set_attribute(SemanticConvetion.GEN_AI_APPLICATION_NAME,
273
+ application_name)
274
+ span.set_attribute(SemanticConvetion.GEN_AI_REQUEST_MODEL,
275
+ kwargs.get("model", "jamba-1.5-mini"))
276
+ span.set_attribute(SemanticConvetion.GEN_AI_REQUEST_TOP_P,
277
+ kwargs.get("top_p", 1.0))
278
+ span.set_attribute(SemanticConvetion.GEN_AI_REQUEST_MAX_TOKENS,
279
+ kwargs.get("max_tokens", -1))
280
+ span.set_attribute(SemanticConvetion.GEN_AI_REQUEST_TEMPERATURE,
281
+ kwargs.get("temperature", 1.0))
282
+ span.set_attribute(SemanticConvetion.GEN_AI_REQUEST_IS_STREAM,
283
+ False)
284
+ if trace_content:
285
+ span.add_event(
286
+ name=SemanticConvetion.GEN_AI_CONTENT_PROMPT_EVENT,
287
+ attributes={
288
+ SemanticConvetion.GEN_AI_CONTENT_PROMPT: prompt,
289
+ },
290
+ )
291
+
292
+ # Set span attributes when tools is not passed to the function call
293
+ if "tools" not in kwargs:
294
+ # Calculate cost of the operation
295
+ cost = get_chat_model_cost(kwargs.get("model", "jamba-1.5-mini"),
296
+ pricing_info, response_dict.get('usage', {}).get('prompt_tokens', None),
297
+ response_dict.get('usage', {}).get('completion_tokens', None))
298
+
299
+ span.set_attribute(SemanticConvetion.GEN_AI_USAGE_PROMPT_TOKENS,
300
+ response_dict.get('usage', {}).get('prompt_tokens', None))
301
+ span.set_attribute(SemanticConvetion.GEN_AI_USAGE_COMPLETION_TOKENS,
302
+ response_dict.get('usage', {}).get('completion_tokens', None))
303
+ span.set_attribute(SemanticConvetion.GEN_AI_USAGE_TOTAL_TOKENS,
304
+ response_dict.get('usage', {}).get('total_tokens', None))
305
+ span.set_attribute(SemanticConvetion.GEN_AI_RESPONSE_FINISH_REASON,
306
+ [response_dict.get('choices', [])[0].get('finish_reason', None)])
307
+ span.set_attribute(SemanticConvetion.GEN_AI_USAGE_COST,
308
+ cost)
309
+
310
+ # Set span attributes for when n = 1 (default)
311
+ if "n" not in kwargs or kwargs["n"] == 1:
312
+ if trace_content:
313
+ span.add_event(
314
+ name=SemanticConvetion.GEN_AI_CONTENT_COMPLETION_EVENT,
315
+ attributes={
316
+ SemanticConvetion.GEN_AI_CONTENT_COMPLETION: response_dict.get('choices', [])[0].get("message").get("content"),
317
+ },
318
+ )
319
+
320
+ # Set span attributes for when n > 0
321
+ else:
322
+ i = 0
323
+ while i < kwargs["n"] and trace_content is True:
324
+ attribute_name = f"gen_ai.content.completion.{i}"
325
+ span.add_event(
326
+ name=attribute_name,
327
+ attributes={
328
+ SemanticConvetion.GEN_AI_CONTENT_COMPLETION: response_dict.get('choices')[i].get("message").get("content"),
329
+ },
330
+ )
331
+ i += 1
332
+
333
+ # Return original response
334
+ return response
335
+
336
+ # Set span attributes when tools is passed to the function call
337
+ elif "tools" in kwargs:
338
+ # Calculate cost of the operation
339
+ cost = get_chat_model_cost(kwargs.get("model", "jamba-1.5-mini"),
340
+ pricing_info, response_dict.get('usage').get('prompt_tokens'),
341
+ response_dict.get('usage').get('completion_tokens'))
342
+ span.add_event(
343
+ name=SemanticConvetion.GEN_AI_CONTENT_COMPLETION_EVENT,
344
+ attributes={
345
+ SemanticConvetion.GEN_AI_CONTENT_COMPLETION: "Function called with tools",
346
+ },
347
+ )
348
+ span.set_attribute(SemanticConvetion.GEN_AI_USAGE_PROMPT_TOKENS,
349
+ response_dict.get('usage').get('prompt_tokens'))
350
+ span.set_attribute(SemanticConvetion.GEN_AI_USAGE_COMPLETION_TOKENS,
351
+ response_dict.get('usage').get('completion_tokens'))
352
+ span.set_attribute(SemanticConvetion.GEN_AI_USAGE_TOTAL_TOKENS,
353
+ response_dict.get('usage').get('total_tokens'))
354
+ span.set_attribute(SemanticConvetion.GEN_AI_USAGE_COST,
355
+ cost)
356
+
357
+ span.set_status(Status(StatusCode.OK))
358
+
359
+ if disable_metrics is False:
360
+ attributes = {
361
+ TELEMETRY_SDK_NAME:
362
+ "openlit",
363
+ SemanticConvetion.GEN_AI_APPLICATION_NAME:
364
+ application_name,
365
+ SemanticConvetion.GEN_AI_SYSTEM:
366
+ SemanticConvetion.GEN_AI_SYSTEM_AI21,
367
+ SemanticConvetion.GEN_AI_ENVIRONMENT:
368
+ environment,
369
+ SemanticConvetion.GEN_AI_TYPE:
370
+ SemanticConvetion.GEN_AI_TYPE_CHAT,
371
+ SemanticConvetion.GEN_AI_REQUEST_MODEL:
372
+ kwargs.get("model", "jamba-1.5-mini")
373
+ }
374
+
375
+ metrics["genai_requests"].add(1, attributes)
376
+ metrics["genai_total_tokens"].add(response_dict.get('usage').get('total_tokens'), attributes)
377
+ metrics["genai_completion_tokens"].add(response_dict.get('usage').get('completion_tokens'), attributes)
378
+ metrics["genai_prompt_tokens"].add(response_dict.get('usage').get('prompt_tokens'), attributes)
379
+ metrics["genai_cost"].record(cost, attributes)
380
+
381
+ # Return original response
382
+ return response
383
+
384
+ except Exception as e:
385
+ handle_exception(span, e)
386
+ logger.error("Error in trace creation: %s", e)
387
+
388
+ # Return original response
389
+ return response
390
+
391
+ return wrapper
392
+
393
+ def chat_rag(gen_ai_endpoint, version, environment, application_name,
394
+ tracer, pricing_info, trace_content, metrics, disable_metrics):
395
+ """
396
+ Generates a telemetry wrapper for chat completions to collect metrics.
397
+
398
+ Args:
399
+ gen_ai_endpoint: Endpoint identifier for logging and tracing.
400
+ version: Version of the monitoring package.
401
+ environment: Deployment environment (e.g., production, staging).
402
+ application_name: Name of the application using the AI21 SDK.
403
+ tracer: OpenTelemetry tracer for creating spans.
404
+ pricing_info: Information used for calculating the cost of AI21 usage.
405
+ trace_content: Flag indicating whether to trace the actual content.
406
+
407
+ Returns:
408
+ A function that wraps the chat completions method to add telemetry.
409
+ """
410
+
411
+ def wrapper(wrapped, instance, args, kwargs):
412
+ """
413
+ Wraps the 'chat.completions' API call to add telemetry.
414
+
415
+ This collects metrics such as execution time, cost, and token usage, and handles errors
416
+ gracefully, adding details to the trace for observability.
417
+
418
+ Args:
419
+ wrapped: The original 'chat.completions' method to be wrapped.
420
+ instance: The instance of the class where the original method is defined.
421
+ args: Positional arguments for the 'chat.completions' method.
422
+ kwargs: Keyword arguments for the 'chat.completions' method.
423
+
424
+ Returns:
425
+ The response from the original 'chat.completions' method.
426
+ """
427
+
428
+ # Check if streaming is enabled for the API call
429
+ streaming = kwargs.get("stream", False)
430
+
431
+ # pylint: disable=no-else-return
432
+ if streaming:
433
+ # # Special handling for streaming response to accommodate the nature of data flow
434
+ # awaited_wrapped = wrapped(*args, **kwargs)
435
+ # span = tracer.start_span(gen_ai_endpoint, kind=SpanKind.CLIENT)
436
+
437
+ # return TracedSyncStream(awaited_wrapped, span, kwargs)
438
+
439
+ return
440
+
441
+ # Handling for non-streaming responses
442
+ else:
443
+ # pylint: disable=line-too-long
444
+ with tracer.start_as_current_span(gen_ai_endpoint, kind= SpanKind.CLIENT) as span:
445
+ response = wrapped(*args, **kwargs)
446
+
447
+ response_dict = response_as_dict(response)
448
+
449
+ try:
450
+ # Format 'messages' into a single string
451
+ message_prompt = kwargs.get("messages", "")
452
+ formatted_messages = []
453
+ for message in message_prompt:
454
+ role = message.role
455
+ content = message.content
456
+
457
+ if isinstance(content, list):
458
+ content_str = ", ".join(
459
+ # pylint: disable=line-too-long
460
+ f'{item["type"]}: {item["text"] if "text" in item else item["image_url"]}'
461
+ if "type" in item else f'text: {item["text"]}'
462
+ for item in content
463
+ )
464
+ formatted_messages.append(f"{role}: {content_str}")
465
+ else:
466
+ formatted_messages.append(f"{role}: {content}")
467
+ prompt = "\n".join(formatted_messages)
468
+
469
+ # Set base span attribues
470
+ span.set_attribute(TELEMETRY_SDK_NAME, "openlit")
471
+ span.set_attribute(SemanticConvetion.GEN_AI_SYSTEM,
472
+ SemanticConvetion.GEN_AI_SYSTEM_AI21)
473
+ span.set_attribute(SemanticConvetion.GEN_AI_TYPE,
474
+ SemanticConvetion.GEN_AI_TYPE_CHAT)
475
+ span.set_attribute(SemanticConvetion.GEN_AI_ENDPOINT,
476
+ gen_ai_endpoint)
477
+ span.set_attribute(SemanticConvetion.GEN_AI_RESPONSE_ID,
478
+ response_dict.get("id"))
479
+ span.set_attribute(SemanticConvetion.GEN_AI_ENVIRONMENT,
480
+ environment)
481
+ span.set_attribute(SemanticConvetion.GEN_AI_APPLICATION_NAME,
482
+ application_name)
483
+ span.set_attribute(SemanticConvetion.GEN_AI_REQUEST_MODEL,
484
+ kwargs.get("model", "jamba-1.5-mini"))
485
+ span.set_attribute(SemanticConvetion.GEN_AI_REQUEST_IS_STREAM,
486
+ False)
487
+ span.set_attribute(SemanticConvetion.GEN_AI_RAG_MAX_SEGMENTS,
488
+ kwargs.get("max_segments", -1))
489
+ span.set_attribute(SemanticConvetion.GEN_AI_RAG_STRATEGY,
490
+ kwargs.get("retrieval_strategy", "segments"))
491
+ span.set_attribute(SemanticConvetion.GEN_AI_RAG_SIMILARITY_THRESHOLD,
492
+ kwargs.get("retrieval_similarity_threshold", -1))
493
+ span.set_attribute(SemanticConvetion.GEN_AI_RAG_MAX_NEIGHBORS,
494
+ kwargs.get("max_neighbors", -1))
495
+ span.set_attribute(SemanticConvetion.GEN_AI_RAG_FILE_IDS,
496
+ str(kwargs.get("file_ids", "")))
497
+ span.set_attribute(SemanticConvetion.GEN_AI_RAG_DOCUMENTS_PATH,
498
+ kwargs.get("path", ""))
499
+
500
+ if trace_content:
501
+ span.add_event(
502
+ name=SemanticConvetion.GEN_AI_CONTENT_PROMPT_EVENT,
503
+ attributes={
504
+ SemanticConvetion.GEN_AI_CONTENT_PROMPT: prompt,
505
+ },
506
+ )
507
+ prompt_tokens = general_tokens(prompt)
508
+
509
+
510
+ # Set span attributes when tools is not passed to the function call
511
+ if "tools" not in kwargs:
512
+ prompt_tokens = general_tokens(prompt)
513
+
514
+ # Set span attributes for when n = 1 (default)
515
+ if "n" not in kwargs or kwargs["n"] == 1:
516
+ completion_tokens = general_tokens(response_dict.get('choices', [])[0].get("content"))
517
+ if trace_content:
518
+ span.add_event(
519
+ name=SemanticConvetion.GEN_AI_CONTENT_COMPLETION_EVENT,
520
+ attributes={
521
+ SemanticConvetion.GEN_AI_CONTENT_COMPLETION: response_dict.get('choices', [])[0].get("content"),
522
+ },
523
+ )
524
+
525
+ # Set span attributes for when n > 0
526
+ else:
527
+ i = 0
528
+ completion_tokens = 0
529
+ while i < kwargs["n"] and trace_content is True:
530
+ completion_tokens += general_tokens(response_dict.get('choices')[i].get("message").get("content"))
531
+ attribute_name = f"gen_ai.content.completion.{i}"
532
+ span.add_event(
533
+ name=attribute_name,
534
+ attributes={
535
+ SemanticConvetion.GEN_AI_CONTENT_COMPLETION: response_dict.get('choices')[i].get("message").get("content"),
536
+ },
537
+ )
538
+ i += 1
539
+
540
+ # Return original response
541
+ return response
542
+
543
+ # Set span attributes when tools is passed to the function call
544
+ elif "tools" in kwargs:
545
+ completion_tokens = -1
546
+ # Calculate cost of the operation
547
+ cost = get_chat_model_cost(kwargs.get("model", "jamba-1.5-mini"),
548
+ pricing_info, response_dict.get('usage').get('prompt_tokens'),
549
+ response_dict.get('usage').get('completion_tokens'))
550
+ span.add_event(
551
+ name=SemanticConvetion.GEN_AI_CONTENT_COMPLETION_EVENT,
552
+ attributes={
553
+ SemanticConvetion.GEN_AI_CONTENT_COMPLETION: "Function called with tools",
554
+ },
555
+ )
556
+ span.set_attribute(SemanticConvetion.GEN_AI_USAGE_PROMPT_TOKENS,
557
+ prompt_tokens)
558
+ span.set_attribute(SemanticConvetion.GEN_AI_USAGE_COMPLETION_TOKENS,
559
+ completion_tokens)
560
+ span.set_attribute(SemanticConvetion.GEN_AI_USAGE_TOTAL_TOKENS,
561
+ prompt_tokens + completion_tokens)
562
+
563
+ # Calculate cost of the operation
564
+ cost = get_chat_model_cost(kwargs.get("model", "jamba-1.5-mini"),
565
+ pricing_info, prompt_tokens,
566
+ completion_tokens)
567
+ span.set_attribute(SemanticConvetion.GEN_AI_USAGE_COST,
568
+ cost)
569
+
570
+ span.set_status(Status(StatusCode.OK))
571
+
572
+ if disable_metrics is False:
573
+ attributes = {
574
+ TELEMETRY_SDK_NAME:
575
+ "openlit",
576
+ SemanticConvetion.GEN_AI_APPLICATION_NAME:
577
+ application_name,
578
+ SemanticConvetion.GEN_AI_SYSTEM:
579
+ SemanticConvetion.GEN_AI_SYSTEM_AI21,
580
+ SemanticConvetion.GEN_AI_ENVIRONMENT:
581
+ environment,
582
+ SemanticConvetion.GEN_AI_TYPE:
583
+ SemanticConvetion.GEN_AI_TYPE_CHAT,
584
+ SemanticConvetion.GEN_AI_REQUEST_MODEL:
585
+ kwargs.get("model", "jamba-1.5-mini")
586
+ }
587
+
588
+ metrics["genai_requests"].add(1, attributes)
589
+ metrics["genai_total_tokens"].add(prompt_tokens + completion_tokens, attributes)
590
+ metrics["genai_completion_tokens"].add(completion_tokens, attributes)
591
+ metrics["genai_prompt_tokens"].add(prompt_tokens, attributes)
592
+ metrics["genai_cost"].record(cost, attributes)
593
+
594
+ # Return original response
595
+ return response
596
+
597
+ except Exception as e:
598
+ handle_exception(span, e)
599
+ logger.error("Error in trace creation: %s", e)
600
+
601
+ # Return original response
602
+ return response
603
+
604
+ return wrapper