openlit 1.33.15__tar.gz → 1.33.16__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 (129) hide show
  1. {openlit-1.33.15 → openlit-1.33.16}/PKG-INFO +1 -1
  2. {openlit-1.33.15 → openlit-1.33.16}/pyproject.toml +1 -1
  3. {openlit-1.33.15 → openlit-1.33.16}/src/openlit/__init__.py +3 -0
  4. {openlit-1.33.15 → openlit-1.33.16}/src/openlit/instrumentation/openai/__init__.py +18 -2
  5. {openlit-1.33.15 → openlit-1.33.16}/src/openlit/instrumentation/openai/async_openai.py +405 -0
  6. {openlit-1.33.15 → openlit-1.33.16}/src/openlit/instrumentation/openai/openai.py +405 -0
  7. openlit-1.33.16/src/openlit/instrumentation/openai_agents/__init__.py +42 -0
  8. openlit-1.33.16/src/openlit/instrumentation/openai_agents/openai_agents.py +65 -0
  9. {openlit-1.33.15 → openlit-1.33.16}/LICENSE +0 -0
  10. {openlit-1.33.15 → openlit-1.33.16}/README.md +0 -0
  11. {openlit-1.33.15 → openlit-1.33.16}/src/openlit/__helpers.py +0 -0
  12. {openlit-1.33.15 → openlit-1.33.16}/src/openlit/evals/__init__.py +0 -0
  13. {openlit-1.33.15 → openlit-1.33.16}/src/openlit/evals/all.py +0 -0
  14. {openlit-1.33.15 → openlit-1.33.16}/src/openlit/evals/bias_detection.py +0 -0
  15. {openlit-1.33.15 → openlit-1.33.16}/src/openlit/evals/hallucination.py +0 -0
  16. {openlit-1.33.15 → openlit-1.33.16}/src/openlit/evals/toxicity.py +0 -0
  17. {openlit-1.33.15 → openlit-1.33.16}/src/openlit/evals/utils.py +0 -0
  18. {openlit-1.33.15 → openlit-1.33.16}/src/openlit/guard/__init__.py +0 -0
  19. {openlit-1.33.15 → openlit-1.33.16}/src/openlit/guard/all.py +0 -0
  20. {openlit-1.33.15 → openlit-1.33.16}/src/openlit/guard/prompt_injection.py +0 -0
  21. {openlit-1.33.15 → openlit-1.33.16}/src/openlit/guard/restrict_topic.py +0 -0
  22. {openlit-1.33.15 → openlit-1.33.16}/src/openlit/guard/sensitive_topic.py +0 -0
  23. {openlit-1.33.15 → openlit-1.33.16}/src/openlit/guard/utils.py +0 -0
  24. {openlit-1.33.15 → openlit-1.33.16}/src/openlit/instrumentation/ag2/__init__.py +0 -0
  25. {openlit-1.33.15 → openlit-1.33.16}/src/openlit/instrumentation/ag2/ag2.py +0 -0
  26. {openlit-1.33.15 → openlit-1.33.16}/src/openlit/instrumentation/ai21/__init__.py +0 -0
  27. {openlit-1.33.15 → openlit-1.33.16}/src/openlit/instrumentation/ai21/ai21.py +0 -0
  28. {openlit-1.33.15 → openlit-1.33.16}/src/openlit/instrumentation/ai21/async_ai21.py +0 -0
  29. {openlit-1.33.15 → openlit-1.33.16}/src/openlit/instrumentation/ai21/utils.py +0 -0
  30. {openlit-1.33.15 → openlit-1.33.16}/src/openlit/instrumentation/anthropic/__init__.py +0 -0
  31. {openlit-1.33.15 → openlit-1.33.16}/src/openlit/instrumentation/anthropic/anthropic.py +0 -0
  32. {openlit-1.33.15 → openlit-1.33.16}/src/openlit/instrumentation/anthropic/async_anthropic.py +0 -0
  33. {openlit-1.33.15 → openlit-1.33.16}/src/openlit/instrumentation/anthropic/utils.py +0 -0
  34. {openlit-1.33.15 → openlit-1.33.16}/src/openlit/instrumentation/assemblyai/__init__.py +0 -0
  35. {openlit-1.33.15 → openlit-1.33.16}/src/openlit/instrumentation/assemblyai/assemblyai.py +0 -0
  36. {openlit-1.33.15 → openlit-1.33.16}/src/openlit/instrumentation/astra/__init__.py +0 -0
  37. {openlit-1.33.15 → openlit-1.33.16}/src/openlit/instrumentation/astra/astra.py +0 -0
  38. {openlit-1.33.15 → openlit-1.33.16}/src/openlit/instrumentation/astra/async_astra.py +0 -0
  39. {openlit-1.33.15 → openlit-1.33.16}/src/openlit/instrumentation/astra/utils.py +0 -0
  40. {openlit-1.33.15 → openlit-1.33.16}/src/openlit/instrumentation/azure_ai_inference/__init__.py +0 -0
  41. {openlit-1.33.15 → openlit-1.33.16}/src/openlit/instrumentation/azure_ai_inference/async_azure_ai_inference.py +0 -0
  42. {openlit-1.33.15 → openlit-1.33.16}/src/openlit/instrumentation/azure_ai_inference/azure_ai_inference.py +0 -0
  43. {openlit-1.33.15 → openlit-1.33.16}/src/openlit/instrumentation/bedrock/__init__.py +0 -0
  44. {openlit-1.33.15 → openlit-1.33.16}/src/openlit/instrumentation/bedrock/bedrock.py +0 -0
  45. {openlit-1.33.15 → openlit-1.33.16}/src/openlit/instrumentation/chroma/__init__.py +0 -0
  46. {openlit-1.33.15 → openlit-1.33.16}/src/openlit/instrumentation/chroma/chroma.py +0 -0
  47. {openlit-1.33.15 → openlit-1.33.16}/src/openlit/instrumentation/cohere/__init__.py +0 -0
  48. {openlit-1.33.15 → openlit-1.33.16}/src/openlit/instrumentation/cohere/async_cohere.py +0 -0
  49. {openlit-1.33.15 → openlit-1.33.16}/src/openlit/instrumentation/cohere/cohere.py +0 -0
  50. {openlit-1.33.15 → openlit-1.33.16}/src/openlit/instrumentation/controlflow/__init__.py +0 -0
  51. {openlit-1.33.15 → openlit-1.33.16}/src/openlit/instrumentation/controlflow/controlflow.py +0 -0
  52. {openlit-1.33.15 → openlit-1.33.16}/src/openlit/instrumentation/crawl4ai/__init__.py +0 -0
  53. {openlit-1.33.15 → openlit-1.33.16}/src/openlit/instrumentation/crawl4ai/async_crawl4ai.py +0 -0
  54. {openlit-1.33.15 → openlit-1.33.16}/src/openlit/instrumentation/crawl4ai/crawl4ai.py +0 -0
  55. {openlit-1.33.15 → openlit-1.33.16}/src/openlit/instrumentation/crewai/__init__.py +0 -0
  56. {openlit-1.33.15 → openlit-1.33.16}/src/openlit/instrumentation/crewai/crewai.py +0 -0
  57. {openlit-1.33.15 → openlit-1.33.16}/src/openlit/instrumentation/dynamiq/__init__.py +0 -0
  58. {openlit-1.33.15 → openlit-1.33.16}/src/openlit/instrumentation/dynamiq/dynamiq.py +0 -0
  59. {openlit-1.33.15 → openlit-1.33.16}/src/openlit/instrumentation/elevenlabs/__init__.py +0 -0
  60. {openlit-1.33.15 → openlit-1.33.16}/src/openlit/instrumentation/elevenlabs/async_elevenlabs.py +0 -0
  61. {openlit-1.33.15 → openlit-1.33.16}/src/openlit/instrumentation/elevenlabs/elevenlabs.py +0 -0
  62. {openlit-1.33.15 → openlit-1.33.16}/src/openlit/instrumentation/embedchain/__init__.py +0 -0
  63. {openlit-1.33.15 → openlit-1.33.16}/src/openlit/instrumentation/embedchain/embedchain.py +0 -0
  64. {openlit-1.33.15 → openlit-1.33.16}/src/openlit/instrumentation/firecrawl/__init__.py +0 -0
  65. {openlit-1.33.15 → openlit-1.33.16}/src/openlit/instrumentation/firecrawl/firecrawl.py +0 -0
  66. {openlit-1.33.15 → openlit-1.33.16}/src/openlit/instrumentation/google_ai_studio/__init__.py +0 -0
  67. {openlit-1.33.15 → openlit-1.33.16}/src/openlit/instrumentation/google_ai_studio/async_google_ai_studio.py +0 -0
  68. {openlit-1.33.15 → openlit-1.33.16}/src/openlit/instrumentation/google_ai_studio/google_ai_studio.py +0 -0
  69. {openlit-1.33.15 → openlit-1.33.16}/src/openlit/instrumentation/gpt4all/__init__.py +0 -0
  70. {openlit-1.33.15 → openlit-1.33.16}/src/openlit/instrumentation/gpt4all/gpt4all.py +0 -0
  71. {openlit-1.33.15 → openlit-1.33.16}/src/openlit/instrumentation/gpu/__init__.py +0 -0
  72. {openlit-1.33.15 → openlit-1.33.16}/src/openlit/instrumentation/groq/__init__.py +0 -0
  73. {openlit-1.33.15 → openlit-1.33.16}/src/openlit/instrumentation/groq/async_groq.py +0 -0
  74. {openlit-1.33.15 → openlit-1.33.16}/src/openlit/instrumentation/groq/groq.py +0 -0
  75. {openlit-1.33.15 → openlit-1.33.16}/src/openlit/instrumentation/haystack/__init__.py +0 -0
  76. {openlit-1.33.15 → openlit-1.33.16}/src/openlit/instrumentation/haystack/haystack.py +0 -0
  77. {openlit-1.33.15 → openlit-1.33.16}/src/openlit/instrumentation/julep/__init__.py +0 -0
  78. {openlit-1.33.15 → openlit-1.33.16}/src/openlit/instrumentation/julep/async_julep.py +0 -0
  79. {openlit-1.33.15 → openlit-1.33.16}/src/openlit/instrumentation/julep/julep.py +0 -0
  80. {openlit-1.33.15 → openlit-1.33.16}/src/openlit/instrumentation/langchain/__init__.py +0 -0
  81. {openlit-1.33.15 → openlit-1.33.16}/src/openlit/instrumentation/langchain/async_langchain.py +0 -0
  82. {openlit-1.33.15 → openlit-1.33.16}/src/openlit/instrumentation/langchain/langchain.py +0 -0
  83. {openlit-1.33.15 → openlit-1.33.16}/src/openlit/instrumentation/letta/__init__.py +0 -0
  84. {openlit-1.33.15 → openlit-1.33.16}/src/openlit/instrumentation/letta/letta.py +0 -0
  85. {openlit-1.33.15 → openlit-1.33.16}/src/openlit/instrumentation/litellm/__init__.py +0 -0
  86. {openlit-1.33.15 → openlit-1.33.16}/src/openlit/instrumentation/litellm/async_litellm.py +0 -0
  87. {openlit-1.33.15 → openlit-1.33.16}/src/openlit/instrumentation/litellm/litellm.py +0 -0
  88. {openlit-1.33.15 → openlit-1.33.16}/src/openlit/instrumentation/llamaindex/__init__.py +0 -0
  89. {openlit-1.33.15 → openlit-1.33.16}/src/openlit/instrumentation/llamaindex/llamaindex.py +0 -0
  90. {openlit-1.33.15 → openlit-1.33.16}/src/openlit/instrumentation/mem0/__init__.py +0 -0
  91. {openlit-1.33.15 → openlit-1.33.16}/src/openlit/instrumentation/mem0/mem0.py +0 -0
  92. {openlit-1.33.15 → openlit-1.33.16}/src/openlit/instrumentation/milvus/__init__.py +0 -0
  93. {openlit-1.33.15 → openlit-1.33.16}/src/openlit/instrumentation/milvus/milvus.py +0 -0
  94. {openlit-1.33.15 → openlit-1.33.16}/src/openlit/instrumentation/mistral/__init__.py +0 -0
  95. {openlit-1.33.15 → openlit-1.33.16}/src/openlit/instrumentation/mistral/async_mistral.py +0 -0
  96. {openlit-1.33.15 → openlit-1.33.16}/src/openlit/instrumentation/mistral/mistral.py +0 -0
  97. {openlit-1.33.15 → openlit-1.33.16}/src/openlit/instrumentation/multion/__init__.py +0 -0
  98. {openlit-1.33.15 → openlit-1.33.16}/src/openlit/instrumentation/multion/async_multion.py +0 -0
  99. {openlit-1.33.15 → openlit-1.33.16}/src/openlit/instrumentation/multion/multion.py +0 -0
  100. {openlit-1.33.15 → openlit-1.33.16}/src/openlit/instrumentation/ollama/__init__.py +0 -0
  101. {openlit-1.33.15 → openlit-1.33.16}/src/openlit/instrumentation/ollama/async_ollama.py +0 -0
  102. {openlit-1.33.15 → openlit-1.33.16}/src/openlit/instrumentation/ollama/ollama.py +0 -0
  103. {openlit-1.33.15 → openlit-1.33.16}/src/openlit/instrumentation/ollama/utils.py +0 -0
  104. {openlit-1.33.15 → openlit-1.33.16}/src/openlit/instrumentation/phidata/__init__.py +0 -0
  105. {openlit-1.33.15 → openlit-1.33.16}/src/openlit/instrumentation/phidata/phidata.py +0 -0
  106. {openlit-1.33.15 → openlit-1.33.16}/src/openlit/instrumentation/pinecone/__init__.py +0 -0
  107. {openlit-1.33.15 → openlit-1.33.16}/src/openlit/instrumentation/pinecone/pinecone.py +0 -0
  108. {openlit-1.33.15 → openlit-1.33.16}/src/openlit/instrumentation/premai/__init__.py +0 -0
  109. {openlit-1.33.15 → openlit-1.33.16}/src/openlit/instrumentation/premai/premai.py +0 -0
  110. {openlit-1.33.15 → openlit-1.33.16}/src/openlit/instrumentation/qdrant/__init__.py +0 -0
  111. {openlit-1.33.15 → openlit-1.33.16}/src/openlit/instrumentation/qdrant/async_qdrant.py +0 -0
  112. {openlit-1.33.15 → openlit-1.33.16}/src/openlit/instrumentation/qdrant/qdrant.py +0 -0
  113. {openlit-1.33.15 → openlit-1.33.16}/src/openlit/instrumentation/reka/__init__.py +0 -0
  114. {openlit-1.33.15 → openlit-1.33.16}/src/openlit/instrumentation/reka/async_reka.py +0 -0
  115. {openlit-1.33.15 → openlit-1.33.16}/src/openlit/instrumentation/reka/reka.py +0 -0
  116. {openlit-1.33.15 → openlit-1.33.16}/src/openlit/instrumentation/together/__init__.py +0 -0
  117. {openlit-1.33.15 → openlit-1.33.16}/src/openlit/instrumentation/together/async_together.py +0 -0
  118. {openlit-1.33.15 → openlit-1.33.16}/src/openlit/instrumentation/together/together.py +0 -0
  119. {openlit-1.33.15 → openlit-1.33.16}/src/openlit/instrumentation/transformers/__init__.py +0 -0
  120. {openlit-1.33.15 → openlit-1.33.16}/src/openlit/instrumentation/transformers/transformers.py +0 -0
  121. {openlit-1.33.15 → openlit-1.33.16}/src/openlit/instrumentation/vertexai/__init__.py +0 -0
  122. {openlit-1.33.15 → openlit-1.33.16}/src/openlit/instrumentation/vertexai/async_vertexai.py +0 -0
  123. {openlit-1.33.15 → openlit-1.33.16}/src/openlit/instrumentation/vertexai/vertexai.py +0 -0
  124. {openlit-1.33.15 → openlit-1.33.16}/src/openlit/instrumentation/vllm/__init__.py +0 -0
  125. {openlit-1.33.15 → openlit-1.33.16}/src/openlit/instrumentation/vllm/vllm.py +0 -0
  126. {openlit-1.33.15 → openlit-1.33.16}/src/openlit/otel/events.py +0 -0
  127. {openlit-1.33.15 → openlit-1.33.16}/src/openlit/otel/metrics.py +0 -0
  128. {openlit-1.33.15 → openlit-1.33.16}/src/openlit/otel/tracing.py +0 -0
  129. {openlit-1.33.15 → openlit-1.33.16}/src/openlit/semcov/__init__.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.3
2
2
  Name: openlit
3
- Version: 1.33.15
3
+ Version: 1.33.16
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
  License: Apache-2.0
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.33.15"
3
+ version = "1.33.16"
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
  license = "Apache-2.0"
@@ -65,6 +65,7 @@ from openlit.instrumentation.controlflow import ControlFlowInstrumentor
65
65
  from openlit.instrumentation.crawl4ai import Crawl4AIInstrumentor
66
66
  from openlit.instrumentation.firecrawl import FireCrawlInstrumentor
67
67
  from openlit.instrumentation.letta import LettaInstrumentor
68
+ from openlit.instrumentation.openai_agents import OpenAIAgentsInstrumentor
68
69
  from openlit.instrumentation.gpu import GPUInstrumentor
69
70
  import openlit.guard
70
71
  import openlit.evals
@@ -293,6 +294,7 @@ def init(
293
294
  "firecrawl": "firecrawl",
294
295
  "letta": "letta",
295
296
  "together": "together",
297
+ "openai-agents": "agents"
296
298
  }
297
299
 
298
300
  invalid_instrumentors = [
@@ -411,6 +413,7 @@ def init(
411
413
  "firecrawl": FireCrawlInstrumentor(),
412
414
  "letta": LettaInstrumentor(),
413
415
  "together": TogetherInstrumentor(),
416
+ "openai-agents": OpenAIAgentsInstrumentor(),
414
417
  }
415
418
 
416
419
  # Initialize and instrument only the enabled instrumentors
@@ -5,11 +5,11 @@ import importlib.metadata
5
5
  from opentelemetry.instrumentation.instrumentor import BaseInstrumentor
6
6
  from wrapt import wrap_function_wrapper
7
7
 
8
- from openlit.instrumentation.openai.openai import chat_completions, embedding
8
+ from openlit.instrumentation.openai.openai import chat_completions, embedding, responses
9
9
  from openlit.instrumentation.openai.openai import image_generate, image_variatons, audio_create
10
10
  from openlit.instrumentation.openai.async_openai import async_chat_completions, async_embedding
11
11
  from openlit.instrumentation.openai.async_openai import async_image_generate, async_image_variatons
12
- from openlit.instrumentation.openai.async_openai import async_audio_create
12
+ from openlit.instrumentation.openai.async_openai import async_audio_create, async_responses
13
13
 
14
14
  _instruments = ("openai >= 1.1.1",)
15
15
 
@@ -45,6 +45,22 @@ class OpenAIInstrumentor(BaseInstrumentor):
45
45
  metrics, disable_metrics),
46
46
  )
47
47
 
48
+ wrap_function_wrapper(
49
+ "openai.resources.responses.responses",
50
+ "Responses.create",
51
+ responses(version, environment, application_name,
52
+ tracer, pricing_info, capture_message_content,
53
+ metrics, disable_metrics),
54
+ )
55
+
56
+ wrap_function_wrapper(
57
+ "openai.resources.responses.responses",
58
+ "AsyncResponses.create",
59
+ async_responses(version, environment, application_name,
60
+ tracer, pricing_info, capture_message_content,
61
+ metrics, disable_metrics),
62
+ )
63
+
48
64
  wrap_function_wrapper(
49
65
  "openai.resources.images",
50
66
  "Images.generate",
@@ -13,6 +13,8 @@ from openlit.__helpers import (
13
13
  get_image_model_cost,
14
14
  general_tokens,
15
15
  handle_exception,
16
+ extract_and_format_input,
17
+ concatenate_all_contents,
16
18
  response_as_dict,
17
19
  calculate_ttft,
18
20
  calculate_tbt,
@@ -24,6 +26,409 @@ from openlit.semcov import SemanticConvetion
24
26
  # Initialize logger for logging potential issues and operations
25
27
  logger = logging.getLogger(__name__)
26
28
 
29
+ def async_responses(version, environment, application_name,
30
+ tracer, pricing_info, capture_message_content, metrics, disable_metrics):
31
+ """
32
+ Generates a telemetry wrapper for chat completions to collect metrics.
33
+
34
+ Args:
35
+ version: Version of the monitoring package.
36
+ environment: Deployment environment (e.g., production, staging).
37
+ application_name: Name of the application using the OpenAI API.
38
+ tracer: OpenTelemetry tracer for creating spans.
39
+ pricing_info: Information used for calculating the cost of OpenAI usage.
40
+ capture_message_content: Flag indicating whether to trace the actual content.
41
+
42
+ Returns:
43
+ A function that wraps the chat completions method to add telemetry.
44
+ """
45
+
46
+ class TracedAsyncStream:
47
+ """
48
+ Wrapper for streaming responses to collect metrics and trace data.
49
+ Wraps the response to collect message IDs and aggregated response.
50
+
51
+ This class implements the '__aiter__' and '__anext__' methods that
52
+ handle asynchronous streaming responses.
53
+
54
+ This class also implements '__aenter__' and '__aexit__' methods that
55
+ handle asynchronous context management protocol.
56
+ """
57
+ def __init__(
58
+ self,
59
+ wrapped,
60
+ span,
61
+ kwargs,
62
+ server_address,
63
+ server_port,
64
+ **args,
65
+ ):
66
+ self.__wrapped__ = wrapped
67
+ self._span = span
68
+ # Placeholder for aggregating streaming response
69
+ self._llmresponse = ""
70
+ self._response_id = ""
71
+ self._response_model = ""
72
+ self._finish_reason = ""
73
+ self._input_tokens = ""
74
+ self._output_tokens = ""
75
+
76
+ self._args = args
77
+ self._kwargs = kwargs
78
+ self._start_time = time.time()
79
+ self._end_time = None
80
+ self._timestamps = []
81
+ self._ttft = 0
82
+ self._tbt = 0
83
+ self._server_address = server_address
84
+ self._server_port = server_port
85
+
86
+ async def __aenter__(self):
87
+ await self.__wrapped__.__aenter__()
88
+ return self
89
+
90
+ async def __aexit__(self, exc_type, exc_value, traceback):
91
+ await self.__wrapped__.__aexit__(exc_type, exc_value, traceback)
92
+
93
+ def __aiter__(self):
94
+ return self
95
+
96
+ async def __getattr__(self, name):
97
+ """Delegate attribute access to the wrapped object."""
98
+ return getattr(await self.__wrapped__, name)
99
+
100
+ async def __anext__(self):
101
+ try:
102
+ chunk = await self.__wrapped__.__anext__()
103
+ end_time = time.time()
104
+ # Record the timestamp for the current chunk
105
+ self._timestamps.append(end_time)
106
+
107
+ if len(self._timestamps) == 1:
108
+ # Calculate time to first chunk
109
+ self._ttft = calculate_ttft(self._timestamps, self._start_time)
110
+
111
+ chunked = response_as_dict(chunk)
112
+ # Collect message IDs and aggregated response from events
113
+ if chunked.get('type') == "response.output_text.delta":
114
+ self._llmresponse += chunked.get('delta')
115
+ if chunked.get('type') == "response.completed":
116
+ self._response_id = chunked.get('response').get('id')
117
+ self._response_model = chunked.get('response').get('model')
118
+ self._finish_reason = chunked.get('response').get('status')
119
+ self._input_tokens = chunked.get('response').get('usage').get('input_tokens')
120
+ self._output_tokens = chunked.get('response').get('usage').get('output_tokens')
121
+ return chunk
122
+ except StopAsyncIteration:
123
+ # Handling exception ensure observability without disrupting operation
124
+ try:
125
+ self._end_time = time.time()
126
+ if len(self._timestamps) > 1:
127
+ self._tbt = calculate_tbt(self._timestamps)
128
+
129
+ try:
130
+ formatted_messages = extract_and_format_input(self._kwargs.get('input', ''))
131
+ prompt = concatenate_all_contents(formatted_messages)
132
+ except:
133
+ prompt = self._kwargs.get('input', '')
134
+
135
+ request_model = self._kwargs.get("model", "gpt-4o")
136
+
137
+ # Calculate cost of the operation
138
+ cost = get_chat_model_cost(request_model,
139
+ pricing_info, self._input_tokens,
140
+ self._output_tokens)
141
+
142
+ # Set Span attributes (OTel Semconv)
143
+ self._span.set_attribute(TELEMETRY_SDK_NAME, "openlit")
144
+ self._span.set_attribute(SemanticConvetion.GEN_AI_OPERATION,
145
+ SemanticConvetion.GEN_AI_OPERATION_TYPE_CHAT)
146
+ self._span.set_attribute(SemanticConvetion.GEN_AI_SYSTEM,
147
+ SemanticConvetion.GEN_AI_SYSTEM_OPENAI)
148
+ self._span.set_attribute(SemanticConvetion.GEN_AI_REQUEST_MODEL,
149
+ request_model)
150
+ self._span.set_attribute(SemanticConvetion.GEN_AI_REQUEST_SEED,
151
+ self._kwargs.get("seed", ""))
152
+ self._span.set_attribute(SemanticConvetion.SERVER_PORT,
153
+ self._server_port)
154
+ self._span.set_attribute(SemanticConvetion.GEN_AI_REQUEST_MAX_TOKENS,
155
+ self._kwargs.get("max_output_tokens", -1))
156
+ self._span.set_attribute(SemanticConvetion.GEN_AI_REQUEST_STOP_SEQUENCES,
157
+ self._kwargs.get("stop", []))
158
+ self._span.set_attribute(SemanticConvetion.GEN_AI_REQUEST_TEMPERATURE,
159
+ self._kwargs.get("temperature", 1.0))
160
+ self._span.set_attribute(SemanticConvetion.GEN_AI_REQUEST_TOP_P,
161
+ self._kwargs.get("top_p", 1.0))
162
+ self._span.set_attribute(SemanticConvetion.GEN_AI_RESPONSE_FINISH_REASON,
163
+ [self._finish_reason])
164
+ self._span.set_attribute(SemanticConvetion.GEN_AI_RESPONSE_ID,
165
+ self._response_id)
166
+ self._span.set_attribute(SemanticConvetion.GEN_AI_RESPONSE_MODEL,
167
+ self._response_model)
168
+ self._span.set_attribute(SemanticConvetion.GEN_AI_USAGE_INPUT_TOKENS,
169
+ self._input_tokens)
170
+ self._span.set_attribute(SemanticConvetion.GEN_AI_USAGE_OUTPUT_TOKENS,
171
+ self._output_tokens)
172
+ self._span.set_attribute(SemanticConvetion.SERVER_ADDRESS,
173
+ self._server_address)
174
+ if isinstance(self._llmresponse, str):
175
+ self._span.set_attribute(SemanticConvetion.GEN_AI_OUTPUT_TYPE,
176
+ "text")
177
+ else:
178
+ self._span.set_attribute(SemanticConvetion.GEN_AI_OUTPUT_TYPE,
179
+ "json")
180
+
181
+ # Set Span attributes (Extra)
182
+ self._span.set_attribute(DEPLOYMENT_ENVIRONMENT,
183
+ environment)
184
+ self._span.set_attribute(SERVICE_NAME,
185
+ application_name)
186
+ self._span.set_attribute(SemanticConvetion.GEN_AI_REQUEST_USER,
187
+ self._kwargs.get("user", ""))
188
+ self._span.set_attribute(SemanticConvetion.GEN_AI_REQUEST_IS_STREAM,
189
+ True)
190
+ self._span.set_attribute(SemanticConvetion.GEN_AI_USAGE_TOTAL_TOKENS,
191
+ self._input_tokens + self._output_tokens)
192
+ self._span.set_attribute(SemanticConvetion.GEN_AI_USAGE_COST,
193
+ cost)
194
+ self._span.set_attribute(SemanticConvetion.GEN_AI_SERVER_TBT,
195
+ self._tbt)
196
+ self._span.set_attribute(SemanticConvetion.GEN_AI_SERVER_TTFT,
197
+ self._ttft)
198
+ self._span.set_attribute(SemanticConvetion.GEN_AI_SDK_VERSION,
199
+ version)
200
+
201
+ if capture_message_content:
202
+ self._span.add_event(
203
+ name=SemanticConvetion.GEN_AI_CONTENT_PROMPT_EVENT,
204
+ attributes={
205
+ SemanticConvetion.GEN_AI_CONTENT_PROMPT: prompt,
206
+ },
207
+ )
208
+ self._span.add_event(
209
+ name=SemanticConvetion.GEN_AI_CONTENT_COMPLETION_EVENT,
210
+ attributes={
211
+ SemanticConvetion.GEN_AI_CONTENT_COMPLETION: self._llmresponse,
212
+ },
213
+ )
214
+ self._span.set_status(Status(StatusCode.OK))
215
+
216
+ if disable_metrics is False:
217
+ attributes = create_metrics_attributes(
218
+ service_name=application_name,
219
+ deployment_environment=environment,
220
+ operation=SemanticConvetion.GEN_AI_OPERATION_TYPE_CHAT,
221
+ system=SemanticConvetion.GEN_AI_SYSTEM_OPENAI,
222
+ request_model=request_model,
223
+ server_address=self._server_address,
224
+ server_port=self._server_port,
225
+ response_model=self._response_model,
226
+ )
227
+
228
+ metrics["genai_client_usage_tokens"].record(
229
+ self._input_tokens + self._output_tokens, attributes
230
+ )
231
+ metrics["genai_client_operation_duration"].record(
232
+ self._end_time - self._start_time, attributes
233
+ )
234
+ metrics["genai_server_tbt"].record(
235
+ self._tbt, attributes
236
+ )
237
+ metrics["genai_server_ttft"].record(
238
+ self._ttft, attributes
239
+ )
240
+ metrics["genai_requests"].add(1, attributes)
241
+ metrics["genai_completion_tokens"].add(self._output_tokens, attributes)
242
+ metrics["genai_prompt_tokens"].add(self._input_tokens, attributes)
243
+ metrics["genai_cost"].record(cost, attributes)
244
+
245
+ except Exception as e:
246
+ handle_exception(self._span, e)
247
+ logger.error("Error in trace creation: %s", e)
248
+ finally:
249
+ self._span.end()
250
+ raise
251
+
252
+ async def wrapper(wrapped, instance, args, kwargs):
253
+ """
254
+ Wraps the 'chat.completions' API call to add telemetry.
255
+
256
+ This collects metrics such as execution time, cost, and token usage, and handles errors
257
+ gracefully, adding details to the trace for observability.
258
+
259
+ Args:
260
+ wrapped: The original 'chat.completions' method to be wrapped.
261
+ instance: The instance of the class where the original method is defined.
262
+ args: Positional arguments for the 'chat.completions' method.
263
+ kwargs: Keyword arguments for the 'chat.completions' method.
264
+
265
+ Returns:
266
+ The response from the original 'chat.completions' method.
267
+ """
268
+
269
+ # Check if streaming is enabled for the API call
270
+ streaming = kwargs.get("stream", False)
271
+ server_address, server_port = set_server_address_and_port(instance, "api.openai.com", 443)
272
+ request_model = kwargs.get("model", "gpt-4o")
273
+
274
+ span_name = f"{SemanticConvetion.GEN_AI_OPERATION_TYPE_CHAT} {request_model}"
275
+
276
+ # pylint: disable=no-else-return
277
+ if streaming:
278
+ # Special handling for streaming response to accommodate the nature of data flow
279
+ awaited_wrapped = await wrapped(*args, **kwargs)
280
+ span = tracer.start_span(span_name, kind=SpanKind.CLIENT)
281
+
282
+ return TracedAsyncStream(awaited_wrapped, span, kwargs, server_address, server_port)
283
+
284
+ # Handling for non-streaming responses
285
+ else:
286
+ with tracer.start_as_current_span(span_name, kind= SpanKind.CLIENT) as span:
287
+ start_time = time.time()
288
+ response = await wrapped(*args, **kwargs)
289
+ end_time = time.time()
290
+
291
+ response_dict = response_as_dict(response)
292
+
293
+ try:
294
+ try:
295
+ formatted_messages = extract_and_format_input(kwargs.get('input', ''))
296
+ prompt = concatenate_all_contents(formatted_messages)
297
+ except:
298
+ prompt = kwargs.get('input', '')
299
+
300
+ input_tokens = response_dict.get('usage').get('input_tokens')
301
+ output_tokens = response_dict.get('usage').get('output_tokens')
302
+
303
+ # Calculate cost of the operation
304
+ cost = get_chat_model_cost(request_model,
305
+ pricing_info, input_tokens,
306
+ output_tokens)
307
+
308
+ # Set base span attribues (OTel Semconv)
309
+ span.set_attribute(TELEMETRY_SDK_NAME, "openlit")
310
+ span.set_attribute(SemanticConvetion.GEN_AI_OPERATION,
311
+ SemanticConvetion.GEN_AI_OPERATION_TYPE_CHAT)
312
+ span.set_attribute(SemanticConvetion.GEN_AI_SYSTEM,
313
+ SemanticConvetion.GEN_AI_SYSTEM_OPENAI)
314
+ span.set_attribute(SemanticConvetion.GEN_AI_REQUEST_MODEL,
315
+ request_model)
316
+ span.set_attribute(SemanticConvetion.GEN_AI_REQUEST_SEED,
317
+ kwargs.get("seed", ""))
318
+ span.set_attribute(SemanticConvetion.SERVER_PORT,
319
+ server_port)
320
+ span.set_attribute(SemanticConvetion.GEN_AI_REQUEST_MAX_TOKENS,
321
+ kwargs.get("max_output_tokens", -1))
322
+ span.set_attribute(SemanticConvetion.GEN_AI_REQUEST_STOP_SEQUENCES,
323
+ kwargs.get("stop", []))
324
+ span.set_attribute(SemanticConvetion.GEN_AI_REQUEST_TEMPERATURE,
325
+ str(response_dict.get("temperature", 1.0)))
326
+ span.set_attribute(SemanticConvetion.GEN_AI_REQUEST_TOP_P,
327
+ str(response_dict.get("top_p", 1.0)))
328
+ span.set_attribute(SemanticConvetion.GEN_AI_RESPONSE_ID,
329
+ response_dict.get("id"))
330
+ span.set_attribute(SemanticConvetion.GEN_AI_RESPONSE_MODEL,
331
+ response_dict.get('model'))
332
+ span.set_attribute(SemanticConvetion.GEN_AI_USAGE_INPUT_TOKENS,
333
+ input_tokens)
334
+ span.set_attribute(SemanticConvetion.GEN_AI_USAGE_OUTPUT_TOKENS,
335
+ output_tokens)
336
+ span.set_attribute(SemanticConvetion.SERVER_ADDRESS,
337
+ server_address)
338
+
339
+ # Set base span attribues (Extras)
340
+ span.set_attribute(DEPLOYMENT_ENVIRONMENT,
341
+ environment)
342
+ span.set_attribute(SERVICE_NAME,
343
+ application_name)
344
+ span.set_attribute(SemanticConvetion.GEN_AI_REQUEST_USER,
345
+ kwargs.get("user", ""))
346
+ span.set_attribute(SemanticConvetion.GEN_AI_REQUEST_IS_STREAM,
347
+ False)
348
+ span.set_attribute(SemanticConvetion.GEN_AI_USAGE_TOTAL_TOKENS,
349
+ input_tokens + output_tokens)
350
+ span.set_attribute(SemanticConvetion.GEN_AI_USAGE_COST,
351
+ cost)
352
+ span.set_attribute(SemanticConvetion.GEN_AI_SERVER_TTFT,
353
+ end_time - start_time)
354
+ span.set_attribute(SemanticConvetion.GEN_AI_SDK_VERSION,
355
+ version)
356
+
357
+ if capture_message_content:
358
+ span.add_event(
359
+ name=SemanticConvetion.GEN_AI_CONTENT_PROMPT_EVENT,
360
+ attributes={
361
+ SemanticConvetion.GEN_AI_CONTENT_PROMPT: prompt,
362
+ },
363
+ )
364
+
365
+ for i in range(kwargs.get('n',1)):
366
+ span.set_attribute(SemanticConvetion.GEN_AI_RESPONSE_FINISH_REASON,
367
+ [response_dict.get('status')])
368
+ try:
369
+ llm_response = str(response_dict.get('output')[i].get('content')[0].get('text',''))
370
+ except:
371
+ llm_response = ''
372
+
373
+ if capture_message_content:
374
+ span.add_event(
375
+ name=SemanticConvetion.GEN_AI_CONTENT_COMPLETION_EVENT,
376
+ attributes={
377
+ # pylint: disable=line-too-long
378
+ SemanticConvetion.GEN_AI_CONTENT_COMPLETION: llm_response,
379
+ },
380
+ )
381
+ if kwargs.get('tools'):
382
+ span.set_attribute(SemanticConvetion.GEN_AI_TOOL_CALLS,
383
+ str(response_dict.get('tools')))
384
+
385
+ if isinstance(llm_response, str):
386
+ span.set_attribute(SemanticConvetion.GEN_AI_OUTPUT_TYPE,
387
+ "text")
388
+ elif llm_response is not None:
389
+ span.set_attribute(SemanticConvetion.GEN_AI_OUTPUT_TYPE,
390
+ "json")
391
+
392
+ span.set_status(Status(StatusCode.OK))
393
+
394
+ if disable_metrics is False:
395
+ attributes = create_metrics_attributes(
396
+ service_name=application_name,
397
+ deployment_environment=environment,
398
+ operation=SemanticConvetion.GEN_AI_OPERATION_TYPE_CHAT,
399
+ system=SemanticConvetion.GEN_AI_SYSTEM_OPENAI,
400
+ request_model=request_model,
401
+ server_address=server_address,
402
+ server_port=server_port,
403
+ response_model=response_dict.get('model'),
404
+ )
405
+
406
+ metrics["genai_client_usage_tokens"].record(
407
+ input_tokens + output_tokens, attributes
408
+ )
409
+ metrics["genai_client_operation_duration"].record(
410
+ end_time - start_time, attributes
411
+ )
412
+ metrics["genai_server_ttft"].record(
413
+ end_time - start_time, attributes
414
+ )
415
+ metrics["genai_requests"].add(1, attributes)
416
+ metrics["genai_completion_tokens"].add(output_tokens, attributes)
417
+ metrics["genai_prompt_tokens"].add(input_tokens, attributes)
418
+ metrics["genai_cost"].record(cost, attributes)
419
+
420
+ # Return original response
421
+ return response
422
+
423
+ except Exception as e:
424
+ handle_exception(span, e)
425
+ logger.error("Error in trace creation: %s", e)
426
+
427
+ # Return original response
428
+ return response
429
+
430
+ return wrapper
431
+
27
432
  def async_chat_completions(version, environment, application_name,
28
433
  tracer, pricing_info, capture_message_content, metrics, disable_metrics):
29
434
  """