openlit 1.29.3__tar.gz → 1.29.4__tar.gz

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.
Files changed (78) hide show
  1. {openlit-1.29.3 → openlit-1.29.4}/PKG-INFO +1 -1
  2. {openlit-1.29.3 → openlit-1.29.4}/pyproject.toml +1 -1
  3. {openlit-1.29.3 → openlit-1.29.4}/src/openlit/__helpers.py +14 -0
  4. {openlit-1.29.3 → openlit-1.29.4}/src/openlit/instrumentation/openai/async_openai.py +61 -34
  5. {openlit-1.29.3 → openlit-1.29.4}/src/openlit/instrumentation/openai/openai.py +206 -154
  6. {openlit-1.29.3 → openlit-1.29.4}/LICENSE +0 -0
  7. {openlit-1.29.3 → openlit-1.29.4}/README.md +0 -0
  8. {openlit-1.29.3 → openlit-1.29.4}/src/openlit/__init__.py +0 -0
  9. {openlit-1.29.3 → openlit-1.29.4}/src/openlit/evals/__init__.py +0 -0
  10. {openlit-1.29.3 → openlit-1.29.4}/src/openlit/evals/all.py +0 -0
  11. {openlit-1.29.3 → openlit-1.29.4}/src/openlit/evals/bias_detection.py +0 -0
  12. {openlit-1.29.3 → openlit-1.29.4}/src/openlit/evals/hallucination.py +0 -0
  13. {openlit-1.29.3 → openlit-1.29.4}/src/openlit/evals/toxicity.py +0 -0
  14. {openlit-1.29.3 → openlit-1.29.4}/src/openlit/evals/utils.py +0 -0
  15. {openlit-1.29.3 → openlit-1.29.4}/src/openlit/guard/__init__.py +0 -0
  16. {openlit-1.29.3 → openlit-1.29.4}/src/openlit/guard/all.py +0 -0
  17. {openlit-1.29.3 → openlit-1.29.4}/src/openlit/guard/prompt_injection.py +0 -0
  18. {openlit-1.29.3 → openlit-1.29.4}/src/openlit/guard/restrict_topic.py +0 -0
  19. {openlit-1.29.3 → openlit-1.29.4}/src/openlit/guard/sensitive_topic.py +0 -0
  20. {openlit-1.29.3 → openlit-1.29.4}/src/openlit/guard/utils.py +0 -0
  21. {openlit-1.29.3 → openlit-1.29.4}/src/openlit/instrumentation/anthropic/__init__.py +0 -0
  22. {openlit-1.29.3 → openlit-1.29.4}/src/openlit/instrumentation/anthropic/anthropic.py +0 -0
  23. {openlit-1.29.3 → openlit-1.29.4}/src/openlit/instrumentation/anthropic/async_anthropic.py +0 -0
  24. {openlit-1.29.3 → openlit-1.29.4}/src/openlit/instrumentation/azure_ai_inference/__init__.py +0 -0
  25. {openlit-1.29.3 → openlit-1.29.4}/src/openlit/instrumentation/azure_ai_inference/async_azure_ai_inference.py +0 -0
  26. {openlit-1.29.3 → openlit-1.29.4}/src/openlit/instrumentation/azure_ai_inference/azure_ai_inference.py +0 -0
  27. {openlit-1.29.3 → openlit-1.29.4}/src/openlit/instrumentation/bedrock/__init__.py +0 -0
  28. {openlit-1.29.3 → openlit-1.29.4}/src/openlit/instrumentation/bedrock/bedrock.py +0 -0
  29. {openlit-1.29.3 → openlit-1.29.4}/src/openlit/instrumentation/chroma/__init__.py +0 -0
  30. {openlit-1.29.3 → openlit-1.29.4}/src/openlit/instrumentation/chroma/chroma.py +0 -0
  31. {openlit-1.29.3 → openlit-1.29.4}/src/openlit/instrumentation/cohere/__init__.py +0 -0
  32. {openlit-1.29.3 → openlit-1.29.4}/src/openlit/instrumentation/cohere/cohere.py +0 -0
  33. {openlit-1.29.3 → openlit-1.29.4}/src/openlit/instrumentation/elevenlabs/__init__.py +0 -0
  34. {openlit-1.29.3 → openlit-1.29.4}/src/openlit/instrumentation/elevenlabs/async_elevenlabs.py +0 -0
  35. {openlit-1.29.3 → openlit-1.29.4}/src/openlit/instrumentation/elevenlabs/elevenlabs.py +0 -0
  36. {openlit-1.29.3 → openlit-1.29.4}/src/openlit/instrumentation/embedchain/__init__.py +0 -0
  37. {openlit-1.29.3 → openlit-1.29.4}/src/openlit/instrumentation/embedchain/embedchain.py +0 -0
  38. {openlit-1.29.3 → openlit-1.29.4}/src/openlit/instrumentation/google_ai_studio/__init__.py +0 -0
  39. {openlit-1.29.3 → openlit-1.29.4}/src/openlit/instrumentation/google_ai_studio/async_google_ai_studio.py +0 -0
  40. {openlit-1.29.3 → openlit-1.29.4}/src/openlit/instrumentation/google_ai_studio/google_ai_studio.py +0 -0
  41. {openlit-1.29.3 → openlit-1.29.4}/src/openlit/instrumentation/gpt4all/__init__.py +0 -0
  42. {openlit-1.29.3 → openlit-1.29.4}/src/openlit/instrumentation/gpt4all/gpt4all.py +0 -0
  43. {openlit-1.29.3 → openlit-1.29.4}/src/openlit/instrumentation/gpu/__init__.py +0 -0
  44. {openlit-1.29.3 → openlit-1.29.4}/src/openlit/instrumentation/groq/__init__.py +0 -0
  45. {openlit-1.29.3 → openlit-1.29.4}/src/openlit/instrumentation/groq/async_groq.py +0 -0
  46. {openlit-1.29.3 → openlit-1.29.4}/src/openlit/instrumentation/groq/groq.py +0 -0
  47. {openlit-1.29.3 → openlit-1.29.4}/src/openlit/instrumentation/haystack/__init__.py +0 -0
  48. {openlit-1.29.3 → openlit-1.29.4}/src/openlit/instrumentation/haystack/haystack.py +0 -0
  49. {openlit-1.29.3 → openlit-1.29.4}/src/openlit/instrumentation/langchain/__init__.py +0 -0
  50. {openlit-1.29.3 → openlit-1.29.4}/src/openlit/instrumentation/langchain/langchain.py +0 -0
  51. {openlit-1.29.3 → openlit-1.29.4}/src/openlit/instrumentation/llamaindex/__init__.py +0 -0
  52. {openlit-1.29.3 → openlit-1.29.4}/src/openlit/instrumentation/llamaindex/llamaindex.py +0 -0
  53. {openlit-1.29.3 → openlit-1.29.4}/src/openlit/instrumentation/milvus/__init__.py +0 -0
  54. {openlit-1.29.3 → openlit-1.29.4}/src/openlit/instrumentation/milvus/milvus.py +0 -0
  55. {openlit-1.29.3 → openlit-1.29.4}/src/openlit/instrumentation/mistral/__init__.py +0 -0
  56. {openlit-1.29.3 → openlit-1.29.4}/src/openlit/instrumentation/mistral/async_mistral.py +0 -0
  57. {openlit-1.29.3 → openlit-1.29.4}/src/openlit/instrumentation/mistral/mistral.py +0 -0
  58. {openlit-1.29.3 → openlit-1.29.4}/src/openlit/instrumentation/ollama/__init__.py +0 -0
  59. {openlit-1.29.3 → openlit-1.29.4}/src/openlit/instrumentation/ollama/async_ollama.py +0 -0
  60. {openlit-1.29.3 → openlit-1.29.4}/src/openlit/instrumentation/ollama/ollama.py +0 -0
  61. {openlit-1.29.3 → openlit-1.29.4}/src/openlit/instrumentation/openai/__init__.py +0 -0
  62. {openlit-1.29.3 → openlit-1.29.4}/src/openlit/instrumentation/openai/async_azure_openai.py +0 -0
  63. {openlit-1.29.3 → openlit-1.29.4}/src/openlit/instrumentation/openai/azure_openai.py +0 -0
  64. {openlit-1.29.3 → openlit-1.29.4}/src/openlit/instrumentation/pinecone/__init__.py +0 -0
  65. {openlit-1.29.3 → openlit-1.29.4}/src/openlit/instrumentation/pinecone/pinecone.py +0 -0
  66. {openlit-1.29.3 → openlit-1.29.4}/src/openlit/instrumentation/qdrant/__init__.py +0 -0
  67. {openlit-1.29.3 → openlit-1.29.4}/src/openlit/instrumentation/qdrant/async_qdrant.py +0 -0
  68. {openlit-1.29.3 → openlit-1.29.4}/src/openlit/instrumentation/qdrant/qdrant.py +0 -0
  69. {openlit-1.29.3 → openlit-1.29.4}/src/openlit/instrumentation/transformers/__init__.py +0 -0
  70. {openlit-1.29.3 → openlit-1.29.4}/src/openlit/instrumentation/transformers/transformers.py +0 -0
  71. {openlit-1.29.3 → openlit-1.29.4}/src/openlit/instrumentation/vertexai/__init__.py +0 -0
  72. {openlit-1.29.3 → openlit-1.29.4}/src/openlit/instrumentation/vertexai/async_vertexai.py +0 -0
  73. {openlit-1.29.3 → openlit-1.29.4}/src/openlit/instrumentation/vertexai/vertexai.py +0 -0
  74. {openlit-1.29.3 → openlit-1.29.4}/src/openlit/instrumentation/vllm/__init__.py +0 -0
  75. {openlit-1.29.3 → openlit-1.29.4}/src/openlit/instrumentation/vllm/vllm.py +0 -0
  76. {openlit-1.29.3 → openlit-1.29.4}/src/openlit/otel/metrics.py +0 -0
  77. {openlit-1.29.3 → openlit-1.29.4}/src/openlit/otel/tracing.py +0 -0
  78. {openlit-1.29.3 → openlit-1.29.4}/src/openlit/semcov/__init__.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.1
2
2
  Name: openlit
3
- Version: 1.29.3
3
+ Version: 1.29.4
4
4
  Summary: OpenTelemetry-native Auto instrumentation library for monitoring LLM Applications and GPUs, facilitating the integration of observability into your GenAI-driven projects
5
5
  Home-page: https://github.com/openlit/openlit/tree/main/openlit/python
6
6
  Keywords: OpenTelemetry,otel,otlp,llm,tracing,openai,anthropic,claude,cohere,llm monitoring,observability,monitoring,gpt,Generative AI,chatGPT,gpu
@@ -1,6 +1,6 @@
1
1
  [tool.poetry]
2
2
  name = "openlit"
3
- version = "1.29.3"
3
+ version = "1.29.4"
4
4
  description = "OpenTelemetry-native Auto instrumentation library for monitoring LLM Applications and GPUs, facilitating the integration of observability into your GenAI-driven projects"
5
5
  authors = ["OpenLIT"]
6
6
  repository = "https://github.com/openlit/openlit/tree/main/openlit/python"
@@ -13,6 +13,20 @@ from opentelemetry.trace import Status, StatusCode
13
13
  # Set up logging
14
14
  logger = logging.getLogger(__name__)
15
15
 
16
+ def response_as_dict(response):
17
+ """
18
+ Return parsed response as a dict
19
+ """
20
+ # pylint: disable=no-else-return
21
+ if isinstance(response, dict):
22
+ return response
23
+ if hasattr(response, "model_dump"):
24
+ return response.model_dump()
25
+ elif hasattr(response, "parse"):
26
+ return response_as_dict(response.parse())
27
+ else:
28
+ return response
29
+
16
30
  def get_env_variable(name, arg_value, error_message):
17
31
  """
18
32
  Retrieve an environment variable if the argument is not provided
@@ -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
@@ -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
@@ -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
@@ -31,10 +38,184 @@ def chat_completions(gen_ai_endpoint, version, environment, application_name,
31
38
  A function that wraps the chat completions method to add telemetry.
32
39
  """
33
40
 
41
+ class TracedSyncStream:
42
+ """
43
+ Wrapper for streaming responses to collect metrics and trace data.
44
+ Wraps the 'openai.AsyncStream' response to collect message IDs and aggregated response.
45
+
46
+ This class implements the '__aiter__' and '__anext__' methods that
47
+ handle asynchronous streaming responses.
48
+
49
+ This class also implements '__aenter__' and '__aexit__' methods that
50
+ handle asynchronous context management protocol.
51
+ """
52
+ def __init__(
53
+ self,
54
+ wrapped,
55
+ span,
56
+ kwargs,
57
+ **args,
58
+ ):
59
+ self.__wrapped__ = wrapped
60
+ self._span = span
61
+ # Placeholder for aggregating streaming response
62
+ self._llmresponse = ""
63
+ self._response_id = ""
64
+
65
+ self._args = args
66
+ self._kwargs = kwargs
67
+
68
+ def __enter__(self):
69
+ self.__wrapped__.__enter__()
70
+ return self
71
+
72
+ def __exit__(self, exc_type, exc_value, traceback):
73
+ self.__wrapped__.__exit__(exc_type, exc_value, traceback)
74
+
75
+ def __iter__(self):
76
+ return self
77
+
78
+ def __getattr__(self, name):
79
+ """Delegate attribute access to the wrapped object."""
80
+ return getattr(self.__wrapped__, name)
81
+
82
+ def __next__(self):
83
+ try:
84
+ chunk = self.__wrapped__.__next__()
85
+ chunked = response_as_dict(chunk)
86
+ # Collect message IDs and aggregated response from events
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')
94
+ return chunk
95
+ except StopIteration:
96
+ # Handling exception ensure observability without disrupting operation
97
+ try:
98
+ # Format 'messages' into a single string
99
+ message_prompt = self._kwargs.get("messages", "")
100
+ formatted_messages = []
101
+ for message in message_prompt:
102
+ role = message["role"]
103
+ content = message["content"]
104
+
105
+ if isinstance(content, list):
106
+ content_str = ", ".join(
107
+ # pylint: disable=line-too-long
108
+ f'{item["type"]}: {item["text"] if "text" in item else item["image_url"]}'
109
+ if "type" in item else f'text: {item["text"]}'
110
+ for item in content
111
+ )
112
+ formatted_messages.append(f"{role}: {content_str}")
113
+ else:
114
+ formatted_messages.append(f"{role}: {content}")
115
+ prompt = "\n".join(formatted_messages)
116
+
117
+ # Calculate tokens using input prompt and aggregated response
118
+ prompt_tokens = openai_tokens(prompt,
119
+ self._kwargs.get("model", "gpt-3.5-turbo"))
120
+ completion_tokens = openai_tokens(self._llmresponse,
121
+ self._kwargs.get("model", "gpt-3.5-turbo"))
122
+
123
+ # Calculate cost of the operation
124
+ cost = get_chat_model_cost(self._kwargs.get("model", "gpt-3.5-turbo"),
125
+ pricing_info, prompt_tokens,
126
+ completion_tokens)
127
+
128
+ # Set Span attributes
129
+ self._span.set_attribute(TELEMETRY_SDK_NAME, "openlit")
130
+ self._span.set_attribute(SemanticConvetion.GEN_AI_SYSTEM,
131
+ SemanticConvetion.GEN_AI_SYSTEM_OPENAI)
132
+ self._span.set_attribute(SemanticConvetion.GEN_AI_TYPE,
133
+ SemanticConvetion.GEN_AI_TYPE_CHAT)
134
+ self._span.set_attribute(SemanticConvetion.GEN_AI_ENDPOINT,
135
+ gen_ai_endpoint)
136
+ self._span.set_attribute(SemanticConvetion.GEN_AI_RESPONSE_ID,
137
+ self._response_id)
138
+ self._span.set_attribute(SemanticConvetion.GEN_AI_ENVIRONMENT,
139
+ environment)
140
+ self._span.set_attribute(SemanticConvetion.GEN_AI_APPLICATION_NAME,
141
+ application_name)
142
+ self._span.set_attribute(SemanticConvetion.GEN_AI_REQUEST_MODEL,
143
+ self._kwargs.get("model", "gpt-3.5-turbo"))
144
+ self._span.set_attribute(SemanticConvetion.GEN_AI_REQUEST_USER,
145
+ self._kwargs.get("user", ""))
146
+ self._span.set_attribute(SemanticConvetion.GEN_AI_REQUEST_TOP_P,
147
+ self._kwargs.get("top_p", 1.0))
148
+ self._span.set_attribute(SemanticConvetion.GEN_AI_REQUEST_MAX_TOKENS,
149
+ self._kwargs.get("max_tokens", -1))
150
+ self._span.set_attribute(SemanticConvetion.GEN_AI_REQUEST_TEMPERATURE,
151
+ self._kwargs.get("temperature", 1.0))
152
+ self._span.set_attribute(SemanticConvetion.GEN_AI_REQUEST_PRESENCE_PENALTY,
153
+ self._kwargs.get("presence_penalty", 0.0))
154
+ self._span.set_attribute(SemanticConvetion.GEN_AI_REQUEST_FREQUENCY_PENALTY,
155
+ self._kwargs.get("frequency_penalty", 0.0))
156
+ self._span.set_attribute(SemanticConvetion.GEN_AI_REQUEST_SEED,
157
+ self._kwargs.get("seed", ""))
158
+ self._span.set_attribute(SemanticConvetion.GEN_AI_REQUEST_IS_STREAM,
159
+ True)
160
+ self._span.set_attribute(SemanticConvetion.GEN_AI_USAGE_PROMPT_TOKENS,
161
+ prompt_tokens)
162
+ self._span.set_attribute(SemanticConvetion.GEN_AI_USAGE_COMPLETION_TOKENS,
163
+ completion_tokens)
164
+ self._span.set_attribute(SemanticConvetion.GEN_AI_USAGE_TOTAL_TOKENS,
165
+ prompt_tokens + completion_tokens)
166
+ self._span.set_attribute(SemanticConvetion.GEN_AI_USAGE_COST,
167
+ cost)
168
+ if trace_content:
169
+ self._span.add_event(
170
+ name=SemanticConvetion.GEN_AI_CONTENT_PROMPT_EVENT,
171
+ attributes={
172
+ SemanticConvetion.GEN_AI_CONTENT_PROMPT: prompt,
173
+ },
174
+ )
175
+ self._span.add_event(
176
+ name=SemanticConvetion.GEN_AI_CONTENT_COMPLETION_EVENT,
177
+ attributes={
178
+ SemanticConvetion.GEN_AI_CONTENT_COMPLETION: self._llmresponse,
179
+ },
180
+ )
181
+
182
+ self._span.set_status(Status(StatusCode.OK))
183
+
184
+ if disable_metrics is False:
185
+ attributes = {
186
+ TELEMETRY_SDK_NAME:
187
+ "openlit",
188
+ SemanticConvetion.GEN_AI_APPLICATION_NAME:
189
+ application_name,
190
+ SemanticConvetion.GEN_AI_SYSTEM:
191
+ SemanticConvetion.GEN_AI_SYSTEM_OPENAI,
192
+ SemanticConvetion.GEN_AI_ENVIRONMENT:
193
+ environment,
194
+ SemanticConvetion.GEN_AI_TYPE:
195
+ SemanticConvetion.GEN_AI_TYPE_CHAT,
196
+ SemanticConvetion.GEN_AI_REQUEST_MODEL:
197
+ self._kwargs.get("model", "gpt-3.5-turbo")
198
+ }
199
+
200
+ metrics["genai_requests"].add(1, attributes)
201
+ metrics["genai_total_tokens"].add(
202
+ prompt_tokens + completion_tokens, attributes
203
+ )
204
+ metrics["genai_completion_tokens"].add(completion_tokens, attributes)
205
+ metrics["genai_prompt_tokens"].add(prompt_tokens, attributes)
206
+ metrics["genai_cost"].record(cost, attributes)
207
+
208
+ except Exception as e:
209
+ handle_exception(self._span, e)
210
+ logger.error("Error in trace creation: %s", e)
211
+ finally:
212
+ self._span.end()
213
+ raise
214
+
34
215
  def wrapper(wrapped, instance, args, kwargs):
35
216
  """
36
217
  Wraps the 'chat.completions' API call to add telemetry.
37
-
218
+
38
219
  This collects metrics such as execution time, cost, and token usage, and handles errors
39
220
  gracefully, adding details to the trace for observability.
40
221
 
@@ -54,141 +235,10 @@ def chat_completions(gen_ai_endpoint, version, environment, application_name,
54
235
  # pylint: disable=no-else-return
55
236
  if streaming:
56
237
  # Special handling for streaming response to accommodate the nature of data flow
57
- def stream_generator():
58
- with tracer.start_as_current_span(gen_ai_endpoint, kind= SpanKind.CLIENT) as span:
59
- # Placeholder for aggregating streaming response
60
- llmresponse = ""
61
-
62
-
63
- # Loop through streaming events capturing relevant details
64
- for chunk in wrapped(*args, **kwargs):
65
- # Collect message IDs and aggregated response from events
66
- if len(chunk.choices) > 0:
67
- # pylint: disable=line-too-long
68
- if hasattr(chunk.choices[0], "delta") and hasattr(chunk.choices[0].delta, "content"):
69
- content = chunk.choices[0].delta.content
70
- if content:
71
- llmresponse += content
72
- yield chunk
73
- response_id = chunk.id
74
-
75
- # Handling exception ensure observability without disrupting operation
76
- try:
77
- # Format 'messages' into a single string
78
- message_prompt = kwargs.get("messages", "")
79
- formatted_messages = []
80
- for message in message_prompt:
81
- role = message["role"]
82
- content = message["content"]
83
-
84
- if isinstance(content, list):
85
- content_str = ", ".join(
86
- # pylint: disable=line-too-long
87
- f'{item["type"]}: {item["text"] if "text" in item else item["image_url"]}'
88
- if "type" in item else f'text: {item["text"]}'
89
- for item in content
90
- )
91
- formatted_messages.append(f"{role}: {content_str}")
92
- else:
93
- formatted_messages.append(f"{role}: {content}")
94
- prompt = "\n".join(formatted_messages)
95
-
96
- # Calculate tokens using input prompt and aggregated response
97
- prompt_tokens = openai_tokens(prompt,
98
- kwargs.get("model", "gpt-3.5-turbo"))
99
- completion_tokens = openai_tokens(llmresponse,
100
- kwargs.get("model", "gpt-3.5-turbo"))
101
-
102
- # Calculate cost of the operation
103
- cost = get_chat_model_cost(kwargs.get("model", "gpt-3.5-turbo"),
104
- pricing_info, prompt_tokens,
105
- completion_tokens)
106
-
107
- # Set Span attributes
108
- span.set_attribute(TELEMETRY_SDK_NAME, "openlit")
109
- span.set_attribute(SemanticConvetion.GEN_AI_SYSTEM,
110
- SemanticConvetion.GEN_AI_SYSTEM_OPENAI)
111
- span.set_attribute(SemanticConvetion.GEN_AI_TYPE,
112
- SemanticConvetion.GEN_AI_TYPE_CHAT)
113
- span.set_attribute(SemanticConvetion.GEN_AI_ENDPOINT,
114
- gen_ai_endpoint)
115
- span.set_attribute(SemanticConvetion.GEN_AI_RESPONSE_ID,
116
- response_id)
117
- span.set_attribute(SemanticConvetion.GEN_AI_ENVIRONMENT,
118
- environment)
119
- span.set_attribute(SemanticConvetion.GEN_AI_APPLICATION_NAME,
120
- application_name)
121
- span.set_attribute(SemanticConvetion.GEN_AI_REQUEST_MODEL,
122
- kwargs.get("model", "gpt-3.5-turbo"))
123
- span.set_attribute(SemanticConvetion.GEN_AI_REQUEST_USER,
124
- kwargs.get("user", ""))
125
- span.set_attribute(SemanticConvetion.GEN_AI_REQUEST_TOP_P,
126
- kwargs.get("top_p", 1.0))
127
- span.set_attribute(SemanticConvetion.GEN_AI_REQUEST_MAX_TOKENS,
128
- kwargs.get("max_tokens", -1))
129
- span.set_attribute(SemanticConvetion.GEN_AI_REQUEST_TEMPERATURE,
130
- kwargs.get("temperature", 1.0))
131
- span.set_attribute(SemanticConvetion.GEN_AI_REQUEST_PRESENCE_PENALTY,
132
- kwargs.get("presence_penalty", 0.0))
133
- span.set_attribute(SemanticConvetion.GEN_AI_REQUEST_FREQUENCY_PENALTY,
134
- kwargs.get("frequency_penalty", 0.0))
135
- span.set_attribute(SemanticConvetion.GEN_AI_REQUEST_SEED,
136
- kwargs.get("seed", ""))
137
- span.set_attribute(SemanticConvetion.GEN_AI_REQUEST_IS_STREAM,
138
- True)
139
- span.set_attribute(SemanticConvetion.GEN_AI_USAGE_PROMPT_TOKENS,
140
- prompt_tokens)
141
- span.set_attribute(SemanticConvetion.GEN_AI_USAGE_COMPLETION_TOKENS,
142
- completion_tokens)
143
- span.set_attribute(SemanticConvetion.GEN_AI_USAGE_TOTAL_TOKENS,
144
- prompt_tokens + completion_tokens)
145
- span.set_attribute(SemanticConvetion.GEN_AI_USAGE_COST,
146
- cost)
147
- if trace_content:
148
- span.add_event(
149
- name=SemanticConvetion.GEN_AI_CONTENT_PROMPT_EVENT,
150
- attributes={
151
- SemanticConvetion.GEN_AI_CONTENT_PROMPT: prompt,
152
- },
153
- )
154
- span.add_event(
155
- name=SemanticConvetion.GEN_AI_CONTENT_COMPLETION_EVENT,
156
- attributes={
157
- SemanticConvetion.GEN_AI_CONTENT_COMPLETION: llmresponse,
158
- },
159
- )
160
-
161
- span.set_status(Status(StatusCode.OK))
162
-
163
- if disable_metrics is False:
164
- attributes = {
165
- TELEMETRY_SDK_NAME:
166
- "openlit",
167
- SemanticConvetion.GEN_AI_APPLICATION_NAME:
168
- application_name,
169
- SemanticConvetion.GEN_AI_SYSTEM:
170
- SemanticConvetion.GEN_AI_SYSTEM_OPENAI,
171
- SemanticConvetion.GEN_AI_ENVIRONMENT:
172
- environment,
173
- SemanticConvetion.GEN_AI_TYPE:
174
- SemanticConvetion.GEN_AI_TYPE_CHAT,
175
- SemanticConvetion.GEN_AI_REQUEST_MODEL:
176
- kwargs.get("model", "gpt-3.5-turbo")
177
- }
178
-
179
- metrics["genai_requests"].add(1, attributes)
180
- metrics["genai_total_tokens"].add(
181
- prompt_tokens + completion_tokens, attributes
182
- )
183
- metrics["genai_completion_tokens"].add(completion_tokens, attributes)
184
- metrics["genai_prompt_tokens"].add(prompt_tokens, attributes)
185
- metrics["genai_cost"].record(cost, attributes)
238
+ awaited_wrapped = wrapped(*args, **kwargs)
239
+ span = tracer.start_span(gen_ai_endpoint, kind=SpanKind.CLIENT)
186
240
 
187
- except Exception as e:
188
- handle_exception(span, e)
189
- logger.error("Error in trace creation: %s", e)
190
-
191
- return stream_generator()
241
+ return TracedSyncStream(awaited_wrapped, span, kwargs)
192
242
 
193
243
  # Handling for non-streaming responses
194
244
  else:
@@ -196,6 +246,8 @@ def chat_completions(gen_ai_endpoint, version, environment, application_name,
196
246
  with tracer.start_as_current_span(gen_ai_endpoint, kind= SpanKind.CLIENT) as span:
197
247
  response = wrapped(*args, **kwargs)
198
248
 
249
+ response_dict = response_as_dict(response)
250
+
199
251
  try:
200
252
  # Format 'messages' into a single string
201
253
  message_prompt = kwargs.get("messages", "")
@@ -225,7 +277,7 @@ def chat_completions(gen_ai_endpoint, version, environment, application_name,
225
277
  span.set_attribute(SemanticConvetion.GEN_AI_ENDPOINT,
226
278
  gen_ai_endpoint)
227
279
  span.set_attribute(SemanticConvetion.GEN_AI_RESPONSE_ID,
228
- response.id)
280
+ response_dict.get("id"))
229
281
  span.set_attribute(SemanticConvetion.GEN_AI_ENVIRONMENT,
230
282
  environment)
231
283
  span.set_attribute(SemanticConvetion.GEN_AI_APPLICATION_NAME,
@@ -260,17 +312,17 @@ def chat_completions(gen_ai_endpoint, version, environment, application_name,
260
312
  if "tools" not in kwargs:
261
313
  # Calculate cost of the operation
262
314
  cost = get_chat_model_cost(kwargs.get("model", "gpt-3.5-turbo"),
263
- pricing_info, response.usage.prompt_tokens,
264
- response.usage.completion_tokens)
315
+ pricing_info, response_dict.get('usage', {}).get('prompt_tokens', None),
316
+ response_dict.get('usage', {}).get('completion_tokens', None))
265
317
 
266
318
  span.set_attribute(SemanticConvetion.GEN_AI_USAGE_PROMPT_TOKENS,
267
- response.usage.prompt_tokens)
319
+ response_dict.get('usage', {}).get('prompt_tokens', None))
268
320
  span.set_attribute(SemanticConvetion.GEN_AI_USAGE_COMPLETION_TOKENS,
269
- response.usage.completion_tokens)
321
+ response_dict.get('usage', {}).get('completion_tokens', None))
270
322
  span.set_attribute(SemanticConvetion.GEN_AI_USAGE_TOTAL_TOKENS,
271
- response.usage.total_tokens)
323
+ response_dict.get('usage', {}).get('total_tokens', None))
272
324
  span.set_attribute(SemanticConvetion.GEN_AI_RESPONSE_FINISH_REASON,
273
- [response.choices[0].finish_reason])
325
+ [response_dict.get('choices', [])[0].get('finish_reason', None)])
274
326
  span.set_attribute(SemanticConvetion.GEN_AI_USAGE_COST,
275
327
  cost)
276
328
 
@@ -280,7 +332,7 @@ def chat_completions(gen_ai_endpoint, version, environment, application_name,
280
332
  span.add_event(
281
333
  name=SemanticConvetion.GEN_AI_CONTENT_COMPLETION_EVENT,
282
334
  attributes={
283
- 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"),
284
336
  },
285
337
  )
286
338
 
@@ -292,7 +344,7 @@ def chat_completions(gen_ai_endpoint, version, environment, application_name,
292
344
  span.add_event(
293
345
  name=attribute_name,
294
346
  attributes={
295
- 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"),
296
348
  },
297
349
  )
298
350
  i += 1
@@ -304,8 +356,8 @@ def chat_completions(gen_ai_endpoint, version, environment, application_name,
304
356
  elif "tools" in kwargs:
305
357
  # Calculate cost of the operation
306
358
  cost = get_chat_model_cost(kwargs.get("model", "gpt-3.5-turbo"),
307
- pricing_info, response.usage.prompt_tokens,
308
- response.usage.completion_tokens)
359
+ pricing_info, response_dict.get('usage').get('prompt_tokens'),
360
+ response_dict.get('usage').get('completion_tokens'))
309
361
  span.add_event(
310
362
  name=SemanticConvetion.GEN_AI_CONTENT_COMPLETION_EVENT,
311
363
  attributes={
@@ -313,11 +365,11 @@ def chat_completions(gen_ai_endpoint, version, environment, application_name,
313
365
  },
314
366
  )
315
367
  span.set_attribute(SemanticConvetion.GEN_AI_USAGE_PROMPT_TOKENS,
316
- response.usage.prompt_tokens)
368
+ response_dict.get('usage').get('prompt_tokens'))
317
369
  span.set_attribute(SemanticConvetion.GEN_AI_USAGE_COMPLETION_TOKENS,
318
- response.usage.completion_tokens)
370
+ response_dict.get('usage').get('completion_tokens'))
319
371
  span.set_attribute(SemanticConvetion.GEN_AI_USAGE_TOTAL_TOKENS,
320
- response.usage.total_tokens)
372
+ response_dict.get('usage').get('total_tokens'))
321
373
  span.set_attribute(SemanticConvetion.GEN_AI_USAGE_COST,
322
374
  cost)
323
375
 
@@ -340,9 +392,9 @@ def chat_completions(gen_ai_endpoint, version, environment, application_name,
340
392
  }
341
393
 
342
394
  metrics["genai_requests"].add(1, attributes)
343
- metrics["genai_total_tokens"].add(response.usage.total_tokens, attributes)
344
- metrics["genai_completion_tokens"].add(response.usage.completion_tokens, attributes)
345
- 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)
346
398
  metrics["genai_cost"].record(cost, attributes)
347
399
 
348
400
  # Return original response
File without changes
File without changes