openlit 1.29.3__py3-none-any.whl → 1.30.0__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,407 @@
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
+ openai_tokens,
12
+ handle_exception,
13
+ response_as_dict,
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 completion(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 OpenAI API.
30
+ tracer: OpenTelemetry tracer for creating spans.
31
+ pricing_info: Information used for calculating the cost of OpenAI 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
+ Wraps the 'openai.AsyncStream' response to collect message IDs and aggregated response.
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
+ def __enter__(self):
66
+ self.__wrapped__.__enter__()
67
+ return self
68
+
69
+ def __exit__(self, exc_type, exc_value, traceback):
70
+ self.__wrapped__.__exit__(exc_type, exc_value, traceback)
71
+
72
+ def __iter__(self):
73
+ return self
74
+
75
+ def __getattr__(self, name):
76
+ """Delegate attribute access to the wrapped object."""
77
+ return getattr(self.__wrapped__, name)
78
+
79
+ def __next__(self):
80
+ try:
81
+ chunk = self.__wrapped__.__next__()
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 StopIteration:
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_OPENAI)
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_OPENAI,
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
+ 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 = wrapped(*args, **kwargs)
236
+ span = tracer.start_span(gen_ai_endpoint, kind=SpanKind.CLIENT)
237
+
238
+ return TracedSyncStream(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 = 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_OPENAI)
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_OPENAI,
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
@@ -6,8 +6,15 @@ Module for monitoring OpenAI API calls.
6
6
  import logging
7
7
  from opentelemetry.trace import SpanKind, Status, StatusCode
8
8
  from opentelemetry.sdk.resources import TELEMETRY_SDK_NAME
9
- from openlit.__helpers import get_chat_model_cost, get_embed_model_cost, get_audio_model_cost
10
- from openlit.__helpers import get_image_model_cost, openai_tokens, handle_exception
9
+ from openlit.__helpers import (
10
+ get_chat_model_cost,
11
+ get_embed_model_cost,
12
+ get_audio_model_cost,
13
+ get_image_model_cost,
14
+ openai_tokens,
15
+ handle_exception,
16
+ response_as_dict,
17
+ )
11
18
  from openlit.semcov import SemanticConvetion
12
19
 
13
20
  # Initialize logger for logging potential issues and operations
@@ -46,8 +53,8 @@ def async_chat_completions(gen_ai_endpoint, version, environment, application_na
46
53
  self,
47
54
  wrapped,
48
55
  span,
49
- *args,
50
- **kwargs,
56
+ kwargs,
57
+ **args,
51
58
  ):
52
59
  self.__wrapped__ = wrapped
53
60
  self._span = span
@@ -68,17 +75,22 @@ def async_chat_completions(gen_ai_endpoint, version, environment, application_na
68
75
  def __aiter__(self):
69
76
  return self
70
77
 
78
+ async def __getattr__(self, name):
79
+ """Delegate attribute access to the wrapped object."""
80
+ return getattr(await self.__wrapped__, name)
81
+
71
82
  async def __anext__(self):
72
83
  try:
73
84
  chunk = await self.__wrapped__.__anext__()
85
+ chunked = response_as_dict(chunk)
74
86
  # Collect message IDs and aggregated response from events
75
- if len(chunk.choices) > 0:
76
- # pylint: disable=line-too-long
77
- if hasattr(chunk.choices[0], "delta") and hasattr(chunk.choices[0].delta, "content"):
78
- content = chunk.choices[0].delta.content
79
- if content:
80
- self._llmresponse += content
81
- self._response_id = chunk.id
87
+ if (len(chunked.get('choices')) > 0 and ('delta' in chunked.get('choices')[0] and
88
+ 'content' in chunked.get('choices')[0].get('delta'))):
89
+
90
+ content = chunked.get('choices')[0].get('delta').get('content')
91
+ if content:
92
+ self._llmresponse += content
93
+ self._response_id = chunked.get('id')
82
94
  return chunk
83
95
  except StopAsyncIteration:
84
96
  # Handling exception ensure observability without disrupting operation
@@ -226,7 +238,7 @@ def async_chat_completions(gen_ai_endpoint, version, environment, application_na
226
238
  awaited_wrapped = await wrapped(*args, **kwargs)
227
239
  span = tracer.start_span(gen_ai_endpoint, kind=SpanKind.CLIENT)
228
240
 
229
- return TracedAsyncStream(awaited_wrapped, span)
241
+ return TracedAsyncStream(awaited_wrapped, span, kwargs)
230
242
 
231
243
  # Handling for non-streaming responses
232
244
  else:
@@ -234,6 +246,8 @@ def async_chat_completions(gen_ai_endpoint, version, environment, application_na
234
246
  with tracer.start_as_current_span(gen_ai_endpoint, kind= SpanKind.CLIENT) as span:
235
247
  response = await wrapped(*args, **kwargs)
236
248
 
249
+ response_dict = response_as_dict(response)
250
+
237
251
  try:
238
252
  # Format 'messages' into a single string
239
253
  message_prompt = kwargs.get("messages", "")
@@ -263,7 +277,7 @@ def async_chat_completions(gen_ai_endpoint, version, environment, application_na
263
277
  span.set_attribute(SemanticConvetion.GEN_AI_ENDPOINT,
264
278
  gen_ai_endpoint)
265
279
  span.set_attribute(SemanticConvetion.GEN_AI_RESPONSE_ID,
266
- response.id)
280
+ response_dict.get("id"))
267
281
  span.set_attribute(SemanticConvetion.GEN_AI_ENVIRONMENT,
268
282
  environment)
269
283
  span.set_attribute(SemanticConvetion.GEN_AI_APPLICATION_NAME,
@@ -294,23 +308,21 @@ def async_chat_completions(gen_ai_endpoint, version, environment, application_na
294
308
  },
295
309
  )
296
310
 
297
- span.set_status(Status(StatusCode.OK))
298
-
299
311
  # Set span attributes when tools is not passed to the function call
300
312
  if "tools" not in kwargs:
301
313
  # Calculate cost of the operation
302
314
  cost = get_chat_model_cost(kwargs.get("model", "gpt-3.5-turbo"),
303
- pricing_info, response.usage.prompt_tokens,
304
- response.usage.completion_tokens)
315
+ pricing_info, response_dict.get('usage', {}).get('prompt_tokens', None),
316
+ response_dict.get('usage', {}).get('completion_tokens', None))
305
317
 
306
318
  span.set_attribute(SemanticConvetion.GEN_AI_USAGE_PROMPT_TOKENS,
307
- response.usage.prompt_tokens)
319
+ response_dict.get('usage', {}).get('prompt_tokens', None))
308
320
  span.set_attribute(SemanticConvetion.GEN_AI_USAGE_COMPLETION_TOKENS,
309
- response.usage.completion_tokens)
321
+ response_dict.get('usage', {}).get('completion_tokens', None))
310
322
  span.set_attribute(SemanticConvetion.GEN_AI_USAGE_TOTAL_TOKENS,
311
- response.usage.total_tokens)
323
+ response_dict.get('usage', {}).get('total_tokens', None))
312
324
  span.set_attribute(SemanticConvetion.GEN_AI_RESPONSE_FINISH_REASON,
313
- [response.choices[0].finish_reason])
325
+ [response_dict.get('choices', [])[0].get('finish_reason', None)])
314
326
  span.set_attribute(SemanticConvetion.GEN_AI_USAGE_COST,
315
327
  cost)
316
328
 
@@ -320,7 +332,7 @@ def async_chat_completions(gen_ai_endpoint, version, environment, application_na
320
332
  span.add_event(
321
333
  name=SemanticConvetion.GEN_AI_CONTENT_COMPLETION_EVENT,
322
334
  attributes={
323
- SemanticConvetion.GEN_AI_CONTENT_COMPLETION: response.choices[0].message.content,
335
+ SemanticConvetion.GEN_AI_CONTENT_COMPLETION: response_dict.get('choices', [])[0].get("message").get("content"),
324
336
  },
325
337
  )
326
338
 
@@ -332,7 +344,7 @@ def async_chat_completions(gen_ai_endpoint, version, environment, application_na
332
344
  span.add_event(
333
345
  name=attribute_name,
334
346
  attributes={
335
- SemanticConvetion.GEN_AI_CONTENT_COMPLETION: response.choices[i].message.content,
347
+ SemanticConvetion.GEN_AI_CONTENT_COMPLETION: response_dict.get('choices')[i].get("message").get("content"),
336
348
  },
337
349
  )
338
350
  i += 1
@@ -344,9 +356,8 @@ def async_chat_completions(gen_ai_endpoint, version, environment, application_na
344
356
  elif "tools" in kwargs:
345
357
  # Calculate cost of the operation
346
358
  cost = get_chat_model_cost(kwargs.get("model", "gpt-3.5-turbo"),
347
- pricing_info, response.usage.prompt_tokens,
348
- response.usage.completion_tokens)
349
-
359
+ pricing_info, response_dict.get('usage').get('prompt_tokens'),
360
+ response_dict.get('usage').get('completion_tokens'))
350
361
  span.add_event(
351
362
  name=SemanticConvetion.GEN_AI_CONTENT_COMPLETION_EVENT,
352
363
  attributes={
@@ -354,11 +365,11 @@ def async_chat_completions(gen_ai_endpoint, version, environment, application_na
354
365
  },
355
366
  )
356
367
  span.set_attribute(SemanticConvetion.GEN_AI_USAGE_PROMPT_TOKENS,
357
- response.usage.prompt_tokens)
368
+ response_dict.get('usage').get('prompt_tokens'))
358
369
  span.set_attribute(SemanticConvetion.GEN_AI_USAGE_COMPLETION_TOKENS,
359
- response.usage.completion_tokens)
370
+ response_dict.get('usage').get('completion_tokens'))
360
371
  span.set_attribute(SemanticConvetion.GEN_AI_USAGE_TOTAL_TOKENS,
361
- response.usage.total_tokens)
372
+ response_dict.get('usage').get('total_tokens'))
362
373
  span.set_attribute(SemanticConvetion.GEN_AI_USAGE_COST,
363
374
  cost)
364
375
 
@@ -381,9 +392,9 @@ def async_chat_completions(gen_ai_endpoint, version, environment, application_na
381
392
  }
382
393
 
383
394
  metrics["genai_requests"].add(1, attributes)
384
- metrics["genai_total_tokens"].add(response.usage.total_tokens, attributes)
385
- metrics["genai_completion_tokens"].add(response.usage.completion_tokens, attributes)
386
- metrics["genai_prompt_tokens"].add(response.usage.prompt_tokens, attributes)
395
+ metrics["genai_total_tokens"].add(response_dict.get('usage').get('total_tokens'), attributes)
396
+ metrics["genai_completion_tokens"].add(response_dict.get('usage').get('completion_tokens'), attributes)
397
+ metrics["genai_prompt_tokens"].add(response_dict.get('usage').get('prompt_tokens'), attributes)
387
398
  metrics["genai_cost"].record(cost, attributes)
388
399
 
389
400
  # Return original response
@@ -457,8 +468,8 @@ def async_embedding(gen_ai_endpoint, version, environment, application_name,
457
468
  kwargs.get("model", "text-embedding-ada-002"))
458
469
  span.set_attribute(SemanticConvetion.GEN_AI_REQUEST_EMBEDDING_FORMAT,
459
470
  kwargs.get("encoding_format", "float"))
460
- span.set_attribute(SemanticConvetion.GEN_AI_REQUEST_EMBEDDING_DIMENSION,
461
- kwargs.get("dimensions", ""))
471
+ # span.set_attribute(SemanticConvetion.GEN_AI_REQUEST_EMBEDDING_DIMENSION,
472
+ # kwargs.get("dimensions", "null"))
462
473
  span.set_attribute(SemanticConvetion.GEN_AI_REQUEST_USER,
463
474
  kwargs.get("user", ""))
464
475
  span.set_attribute(SemanticConvetion.GEN_AI_USAGE_PROMPT_TOKENS,
@@ -548,13 +559,14 @@ def async_finetune(gen_ai_endpoint, version, environment, application_name,
548
559
  with tracer.start_as_current_span(gen_ai_endpoint, kind= SpanKind.CLIENT) as span:
549
560
  response = await wrapped(*args, **kwargs)
550
561
 
562
+ # Handling exception ensure observability without disrupting operation
551
563
  try:
552
564
  # Set Span attributes
553
565
  span.set_attribute(TELEMETRY_SDK_NAME, "openlit")
554
566
  span.set_attribute(SemanticConvetion.GEN_AI_SYSTEM,
555
567
  SemanticConvetion.GEN_AI_SYSTEM_OPENAI)
556
568
  span.set_attribute(SemanticConvetion.GEN_AI_TYPE,
557
- "fine_tuning")
569
+ SemanticConvetion.GEN_AI_TYPE_FINETUNING)
558
570
  span.set_attribute(SemanticConvetion.GEN_AI_ENDPOINT,
559
571
  gen_ai_endpoint)
560
572
  span.set_attribute(SemanticConvetion.GEN_AI_ENVIRONMENT,
@@ -585,7 +597,22 @@ def async_finetune(gen_ai_endpoint, version, environment, application_name,
585
597
  span.set_status(Status(StatusCode.OK))
586
598
 
587
599
  if disable_metrics is False:
588
- metrics["genai_requests"].add(1)
600
+ attributes = {
601
+ TELEMETRY_SDK_NAME:
602
+ "openlit",
603
+ SemanticConvetion.GEN_AI_APPLICATION_NAME:
604
+ application_name,
605
+ SemanticConvetion.GEN_AI_SYSTEM:
606
+ SemanticConvetion.GEN_AI_SYSTEM_OPENAI,
607
+ SemanticConvetion.GEN_AI_ENVIRONMENT:
608
+ environment,
609
+ SemanticConvetion.GEN_AI_TYPE:
610
+ SemanticConvetion.GEN_AI_TYPE_FINETUNING,
611
+ SemanticConvetion.GEN_AI_REQUEST_MODEL:
612
+ kwargs.get("model", "gpt-3.5-turbo")
613
+ }
614
+
615
+ metrics["genai_requests"].add(1, attributes)
589
616
 
590
617
  # Return original response
591
618
  return response