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