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,603 @@
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 async_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 TracedAsyncStream:
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
+ async def __aenter__(self):
67
+ await self.__wrapped__.__aenter__()
68
+ return self
69
+
70
+ async def __aexit__(self, exc_type, exc_value, traceback):
71
+ await self.__wrapped__.__aexit__(exc_type, exc_value, traceback)
72
+
73
+ def __aiter__(self):
74
+ return self
75
+
76
+ async def __getattr__(self, name):
77
+ """Delegate attribute access to the wrapped object."""
78
+ return getattr(await self.__wrapped__, name)
79
+
80
+ async def __anext__(self):
81
+ try:
82
+ chunk = await self.__wrapped__.__anext__()
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 StopAsyncIteration:
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
+ async 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
+ # pylint: disable=no-else-return
224
+ if streaming:
225
+ # Special handling for streaming response to accommodate the nature of data flow
226
+ awaited_wrapped = await wrapped(*args, **kwargs)
227
+ span = tracer.start_span(gen_ai_endpoint, kind=SpanKind.CLIENT)
228
+
229
+ return TracedAsyncStream(awaited_wrapped, span, kwargs)
230
+
231
+ # Handling for non-streaming responses
232
+ else:
233
+ # pylint: disable=line-too-long
234
+ with tracer.start_as_current_span(gen_ai_endpoint, kind= SpanKind.CLIENT) as span:
235
+ response = await wrapped(*args, **kwargs)
236
+
237
+ response_dict = response_as_dict(response)
238
+
239
+ try:
240
+ # Format 'messages' into a single string
241
+ message_prompt = kwargs.get("messages", "")
242
+ formatted_messages = []
243
+ for message in message_prompt:
244
+ role = message.role
245
+ content = message.content
246
+
247
+ if isinstance(content, list):
248
+ content_str = ", ".join(
249
+ # pylint: disable=line-too-long
250
+ f'{item["type"]}: {item["text"] if "text" in item else item["image_url"]}'
251
+ if "type" in item else f'text: {item["text"]}'
252
+ for item in content
253
+ )
254
+ formatted_messages.append(f"{role}: {content_str}")
255
+ else:
256
+ formatted_messages.append(f"{role}: {content}")
257
+ prompt = "\n".join(formatted_messages)
258
+
259
+ # Set base span attribues
260
+ span.set_attribute(TELEMETRY_SDK_NAME, "openlit")
261
+ span.set_attribute(SemanticConvetion.GEN_AI_SYSTEM,
262
+ SemanticConvetion.GEN_AI_SYSTEM_AI21)
263
+ span.set_attribute(SemanticConvetion.GEN_AI_TYPE,
264
+ SemanticConvetion.GEN_AI_TYPE_CHAT)
265
+ span.set_attribute(SemanticConvetion.GEN_AI_ENDPOINT,
266
+ gen_ai_endpoint)
267
+ span.set_attribute(SemanticConvetion.GEN_AI_RESPONSE_ID,
268
+ response_dict.get("id"))
269
+ span.set_attribute(SemanticConvetion.GEN_AI_ENVIRONMENT,
270
+ environment)
271
+ span.set_attribute(SemanticConvetion.GEN_AI_APPLICATION_NAME,
272
+ application_name)
273
+ span.set_attribute(SemanticConvetion.GEN_AI_REQUEST_MODEL,
274
+ kwargs.get("model", "jamba-1.5-mini"))
275
+ span.set_attribute(SemanticConvetion.GEN_AI_REQUEST_TOP_P,
276
+ kwargs.get("top_p", 1.0))
277
+ span.set_attribute(SemanticConvetion.GEN_AI_REQUEST_MAX_TOKENS,
278
+ kwargs.get("max_tokens", -1))
279
+ span.set_attribute(SemanticConvetion.GEN_AI_REQUEST_TEMPERATURE,
280
+ kwargs.get("temperature", 1.0))
281
+ span.set_attribute(SemanticConvetion.GEN_AI_REQUEST_IS_STREAM,
282
+ False)
283
+ if trace_content:
284
+ span.add_event(
285
+ name=SemanticConvetion.GEN_AI_CONTENT_PROMPT_EVENT,
286
+ attributes={
287
+ SemanticConvetion.GEN_AI_CONTENT_PROMPT: prompt,
288
+ },
289
+ )
290
+
291
+ # Set span attributes when tools is not passed to the function call
292
+ if "tools" not in kwargs:
293
+ # Calculate cost of the operation
294
+ cost = get_chat_model_cost(kwargs.get("model", "jamba-1.5-mini"),
295
+ pricing_info, response_dict.get('usage', {}).get('prompt_tokens', None),
296
+ response_dict.get('usage', {}).get('completion_tokens', None))
297
+
298
+ span.set_attribute(SemanticConvetion.GEN_AI_USAGE_PROMPT_TOKENS,
299
+ response_dict.get('usage', {}).get('prompt_tokens', None))
300
+ span.set_attribute(SemanticConvetion.GEN_AI_USAGE_COMPLETION_TOKENS,
301
+ response_dict.get('usage', {}).get('completion_tokens', None))
302
+ span.set_attribute(SemanticConvetion.GEN_AI_USAGE_TOTAL_TOKENS,
303
+ response_dict.get('usage', {}).get('total_tokens', None))
304
+ span.set_attribute(SemanticConvetion.GEN_AI_RESPONSE_FINISH_REASON,
305
+ [response_dict.get('choices', [])[0].get('finish_reason', None)])
306
+ span.set_attribute(SemanticConvetion.GEN_AI_USAGE_COST,
307
+ cost)
308
+
309
+ # Set span attributes for when n = 1 (default)
310
+ if "n" not in kwargs or kwargs["n"] == 1:
311
+ if trace_content:
312
+ span.add_event(
313
+ name=SemanticConvetion.GEN_AI_CONTENT_COMPLETION_EVENT,
314
+ attributes={
315
+ SemanticConvetion.GEN_AI_CONTENT_COMPLETION: response_dict.get('choices', [])[0].get("message").get("content"),
316
+ },
317
+ )
318
+
319
+ # Set span attributes for when n > 0
320
+ else:
321
+ i = 0
322
+ while i < kwargs["n"] and trace_content is True:
323
+ attribute_name = f"gen_ai.content.completion.{i}"
324
+ span.add_event(
325
+ name=attribute_name,
326
+ attributes={
327
+ SemanticConvetion.GEN_AI_CONTENT_COMPLETION: response_dict.get('choices')[i].get("message").get("content"),
328
+ },
329
+ )
330
+ i += 1
331
+
332
+ # Return original response
333
+ return response
334
+
335
+ # Set span attributes when tools is passed to the function call
336
+ elif "tools" in kwargs:
337
+ # Calculate cost of the operation
338
+ cost = get_chat_model_cost(kwargs.get("model", "jamba-1.5-mini"),
339
+ pricing_info, response_dict.get('usage').get('prompt_tokens'),
340
+ response_dict.get('usage').get('completion_tokens'))
341
+ span.add_event(
342
+ name=SemanticConvetion.GEN_AI_CONTENT_COMPLETION_EVENT,
343
+ attributes={
344
+ SemanticConvetion.GEN_AI_CONTENT_COMPLETION: "Function called with tools",
345
+ },
346
+ )
347
+ span.set_attribute(SemanticConvetion.GEN_AI_USAGE_PROMPT_TOKENS,
348
+ response_dict.get('usage').get('prompt_tokens'))
349
+ span.set_attribute(SemanticConvetion.GEN_AI_USAGE_COMPLETION_TOKENS,
350
+ response_dict.get('usage').get('completion_tokens'))
351
+ span.set_attribute(SemanticConvetion.GEN_AI_USAGE_TOTAL_TOKENS,
352
+ response_dict.get('usage').get('total_tokens'))
353
+ span.set_attribute(SemanticConvetion.GEN_AI_USAGE_COST,
354
+ cost)
355
+
356
+ span.set_status(Status(StatusCode.OK))
357
+
358
+ if disable_metrics is False:
359
+ attributes = {
360
+ TELEMETRY_SDK_NAME:
361
+ "openlit",
362
+ SemanticConvetion.GEN_AI_APPLICATION_NAME:
363
+ application_name,
364
+ SemanticConvetion.GEN_AI_SYSTEM:
365
+ SemanticConvetion.GEN_AI_SYSTEM_AI21,
366
+ SemanticConvetion.GEN_AI_ENVIRONMENT:
367
+ environment,
368
+ SemanticConvetion.GEN_AI_TYPE:
369
+ SemanticConvetion.GEN_AI_TYPE_CHAT,
370
+ SemanticConvetion.GEN_AI_REQUEST_MODEL:
371
+ kwargs.get("model", "jamba-1.5-mini")
372
+ }
373
+
374
+ metrics["genai_requests"].add(1, attributes)
375
+ metrics["genai_total_tokens"].add(response_dict.get('usage').get('total_tokens'), attributes)
376
+ metrics["genai_completion_tokens"].add(response_dict.get('usage').get('completion_tokens'), attributes)
377
+ metrics["genai_prompt_tokens"].add(response_dict.get('usage').get('prompt_tokens'), attributes)
378
+ metrics["genai_cost"].record(cost, attributes)
379
+
380
+ # Return original response
381
+ return response
382
+
383
+ except Exception as e:
384
+ handle_exception(span, e)
385
+ logger.error("Error in trace creation: %s", e)
386
+
387
+ # Return original response
388
+ return response
389
+
390
+ return wrapper
391
+
392
+ def async_chat_rag(gen_ai_endpoint, version, environment, application_name,
393
+ tracer, pricing_info, trace_content, metrics, disable_metrics):
394
+ """
395
+ Generates a telemetry wrapper for chat completions to collect metrics.
396
+
397
+ Args:
398
+ gen_ai_endpoint: Endpoint identifier for logging and tracing.
399
+ version: Version of the monitoring package.
400
+ environment: Deployment environment (e.g., production, staging).
401
+ application_name: Name of the application using the AI21 SDK.
402
+ tracer: OpenTelemetry tracer for creating spans.
403
+ pricing_info: Information used for calculating the cost of AI21 usage.
404
+ trace_content: Flag indicating whether to trace the actual content.
405
+
406
+ Returns:
407
+ A function that wraps the chat completions method to add telemetry.
408
+ """
409
+
410
+ async def wrapper(wrapped, instance, args, kwargs):
411
+ """
412
+ Wraps the 'chat.completions' API call to add telemetry.
413
+
414
+ This collects metrics such as execution time, cost, and token usage, and handles errors
415
+ gracefully, adding details to the trace for observability.
416
+
417
+ Args:
418
+ wrapped: The original 'chat.completions' method to be wrapped.
419
+ instance: The instance of the class where the original method is defined.
420
+ args: Positional arguments for the 'chat.completions' method.
421
+ kwargs: Keyword arguments for the 'chat.completions' method.
422
+
423
+ Returns:
424
+ The response from the original 'chat.completions' method.
425
+ """
426
+
427
+ # Check if streaming is enabled for the API call
428
+ streaming = kwargs.get("stream", False)
429
+
430
+ # pylint: disable=no-else-return
431
+ if streaming:
432
+ # # Special handling for streaming response to accommodate the nature of data flow
433
+ # awaited_wrapped = wrapped(*args, **kwargs)
434
+ # span = tracer.start_span(gen_ai_endpoint, kind=SpanKind.CLIENT)
435
+
436
+ # return TracedSyncStream(awaited_wrapped, span, kwargs)
437
+
438
+ return
439
+
440
+ # Handling for non-streaming responses
441
+ else:
442
+ # pylint: disable=line-too-long
443
+ with tracer.start_as_current_span(gen_ai_endpoint, kind= SpanKind.CLIENT) as span:
444
+ response = await wrapped(*args, **kwargs)
445
+
446
+ response_dict = response_as_dict(response)
447
+
448
+ try:
449
+ # Format 'messages' into a single string
450
+ message_prompt = kwargs.get("messages", "")
451
+ formatted_messages = []
452
+ for message in message_prompt:
453
+ role = message.role
454
+ content = message.content
455
+
456
+ if isinstance(content, list):
457
+ content_str = ", ".join(
458
+ # pylint: disable=line-too-long
459
+ f'{item["type"]}: {item["text"] if "text" in item else item["image_url"]}'
460
+ if "type" in item else f'text: {item["text"]}'
461
+ for item in content
462
+ )
463
+ formatted_messages.append(f"{role}: {content_str}")
464
+ else:
465
+ formatted_messages.append(f"{role}: {content}")
466
+ prompt = "\n".join(formatted_messages)
467
+
468
+ # Set base span attribues
469
+ span.set_attribute(TELEMETRY_SDK_NAME, "openlit")
470
+ span.set_attribute(SemanticConvetion.GEN_AI_SYSTEM,
471
+ SemanticConvetion.GEN_AI_SYSTEM_AI21)
472
+ span.set_attribute(SemanticConvetion.GEN_AI_TYPE,
473
+ SemanticConvetion.GEN_AI_TYPE_CHAT)
474
+ span.set_attribute(SemanticConvetion.GEN_AI_ENDPOINT,
475
+ gen_ai_endpoint)
476
+ span.set_attribute(SemanticConvetion.GEN_AI_RESPONSE_ID,
477
+ response_dict.get("id"))
478
+ span.set_attribute(SemanticConvetion.GEN_AI_ENVIRONMENT,
479
+ environment)
480
+ span.set_attribute(SemanticConvetion.GEN_AI_APPLICATION_NAME,
481
+ application_name)
482
+ span.set_attribute(SemanticConvetion.GEN_AI_REQUEST_MODEL,
483
+ kwargs.get("model", "jamba-1.5-mini"))
484
+ span.set_attribute(SemanticConvetion.GEN_AI_REQUEST_IS_STREAM,
485
+ False)
486
+ span.set_attribute(SemanticConvetion.GEN_AI_RAG_MAX_SEGMENTS,
487
+ kwargs.get("max_segments", -1))
488
+ span.set_attribute(SemanticConvetion.GEN_AI_RAG_STRATEGY,
489
+ kwargs.get("retrieval_strategy", "segments"))
490
+ span.set_attribute(SemanticConvetion.GEN_AI_RAG_SIMILARITY_THRESHOLD,
491
+ kwargs.get("retrieval_similarity_threshold", -1))
492
+ span.set_attribute(SemanticConvetion.GEN_AI_RAG_MAX_NEIGHBORS,
493
+ kwargs.get("max_neighbors", -1))
494
+ span.set_attribute(SemanticConvetion.GEN_AI_RAG_FILE_IDS,
495
+ str(kwargs.get("file_ids", "")))
496
+ span.set_attribute(SemanticConvetion.GEN_AI_RAG_DOCUMENTS_PATH,
497
+ kwargs.get("path", ""))
498
+
499
+ if trace_content:
500
+ span.add_event(
501
+ name=SemanticConvetion.GEN_AI_CONTENT_PROMPT_EVENT,
502
+ attributes={
503
+ SemanticConvetion.GEN_AI_CONTENT_PROMPT: prompt,
504
+ },
505
+ )
506
+ prompt_tokens = general_tokens(prompt)
507
+
508
+
509
+ # Set span attributes when tools is not passed to the function call
510
+ if "tools" not in kwargs:
511
+ prompt_tokens = general_tokens(prompt)
512
+
513
+ # Set span attributes for when n = 1 (default)
514
+ if "n" not in kwargs or kwargs["n"] == 1:
515
+ completion_tokens = general_tokens(response_dict.get('choices', [])[0].get("content"))
516
+ if trace_content:
517
+ span.add_event(
518
+ name=SemanticConvetion.GEN_AI_CONTENT_COMPLETION_EVENT,
519
+ attributes={
520
+ SemanticConvetion.GEN_AI_CONTENT_COMPLETION: response_dict.get('choices', [])[0].get("content"),
521
+ },
522
+ )
523
+
524
+ # Set span attributes for when n > 0
525
+ else:
526
+ i = 0
527
+ completion_tokens = 0
528
+ while i < kwargs["n"] and trace_content is True:
529
+ completion_tokens += general_tokens(response_dict.get('choices')[i].get("message").get("content"))
530
+ attribute_name = f"gen_ai.content.completion.{i}"
531
+ span.add_event(
532
+ name=attribute_name,
533
+ attributes={
534
+ SemanticConvetion.GEN_AI_CONTENT_COMPLETION: response_dict.get('choices')[i].get("message").get("content"),
535
+ },
536
+ )
537
+ i += 1
538
+
539
+ # Return original response
540
+ return response
541
+
542
+ # Set span attributes when tools is passed to the function call
543
+ elif "tools" in kwargs:
544
+ completion_tokens = -1
545
+ # Calculate cost of the operation
546
+ cost = get_chat_model_cost(kwargs.get("model", "jamba-1.5-mini"),
547
+ pricing_info, response_dict.get('usage').get('prompt_tokens'),
548
+ response_dict.get('usage').get('completion_tokens'))
549
+ span.add_event(
550
+ name=SemanticConvetion.GEN_AI_CONTENT_COMPLETION_EVENT,
551
+ attributes={
552
+ SemanticConvetion.GEN_AI_CONTENT_COMPLETION: "Function called with tools",
553
+ },
554
+ )
555
+ span.set_attribute(SemanticConvetion.GEN_AI_USAGE_PROMPT_TOKENS,
556
+ prompt_tokens)
557
+ span.set_attribute(SemanticConvetion.GEN_AI_USAGE_COMPLETION_TOKENS,
558
+ completion_tokens)
559
+ span.set_attribute(SemanticConvetion.GEN_AI_USAGE_TOTAL_TOKENS,
560
+ prompt_tokens + completion_tokens)
561
+
562
+ # Calculate cost of the operation
563
+ cost = get_chat_model_cost(kwargs.get("model", "jamba-1.5-mini"),
564
+ pricing_info, prompt_tokens,
565
+ completion_tokens)
566
+ span.set_attribute(SemanticConvetion.GEN_AI_USAGE_COST,
567
+ cost)
568
+
569
+ span.set_status(Status(StatusCode.OK))
570
+
571
+ if disable_metrics is False:
572
+ attributes = {
573
+ TELEMETRY_SDK_NAME:
574
+ "openlit",
575
+ SemanticConvetion.GEN_AI_APPLICATION_NAME:
576
+ application_name,
577
+ SemanticConvetion.GEN_AI_SYSTEM:
578
+ SemanticConvetion.GEN_AI_SYSTEM_AI21,
579
+ SemanticConvetion.GEN_AI_ENVIRONMENT:
580
+ environment,
581
+ SemanticConvetion.GEN_AI_TYPE:
582
+ SemanticConvetion.GEN_AI_TYPE_CHAT,
583
+ SemanticConvetion.GEN_AI_REQUEST_MODEL:
584
+ kwargs.get("model", "jamba-1.5-mini")
585
+ }
586
+
587
+ metrics["genai_requests"].add(1, attributes)
588
+ metrics["genai_total_tokens"].add(prompt_tokens + completion_tokens, attributes)
589
+ metrics["genai_completion_tokens"].add(completion_tokens, attributes)
590
+ metrics["genai_prompt_tokens"].add(prompt_tokens, attributes)
591
+ metrics["genai_cost"].record(cost, attributes)
592
+
593
+ # Return original response
594
+ return response
595
+
596
+ except Exception as e:
597
+ handle_exception(span, e)
598
+ logger.error("Error in trace creation: %s", e)
599
+
600
+ # Return original response
601
+ return response
602
+
603
+ return wrapper