openlit 1.29.4__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.
openlit/__init__.py CHANGED
@@ -46,6 +46,8 @@ from openlit.instrumentation.pinecone import PineconeInstrumentor
46
46
  from openlit.instrumentation.qdrant import QdrantInstrumentor
47
47
  from openlit.instrumentation.milvus import MilvusInstrumentor
48
48
  from openlit.instrumentation.transformers import TransformersInstrumentor
49
+ from openlit.instrumentation.litellm import LiteLLMInstrumentor
50
+ from openlit.instrumentation.crewai import CrewAIInstrumentor
49
51
  from openlit.instrumentation.gpu import GPUInstrumentor
50
52
  import openlit.guard
51
53
  import openlit.evals
@@ -228,6 +230,8 @@ def init(environment="default", application_name="default", tracer=None, otlp_en
228
230
  "qdrant": "qdrant_client",
229
231
  "milvus": "pymilvus",
230
232
  "transformers": "transformers",
233
+ "litellm": "litellm",
234
+ "crewai": "crewai",
231
235
  }
232
236
 
233
237
  invalid_instrumentors = [
@@ -305,6 +309,8 @@ def init(environment="default", application_name="default", tracer=None, otlp_en
305
309
  "qdrant": QdrantInstrumentor(),
306
310
  "milvus": MilvusInstrumentor(),
307
311
  "transformers": TransformersInstrumentor(),
312
+ "litellm": LiteLLMInstrumentor(),
313
+ "crewai": CrewAIInstrumentor(),
308
314
  }
309
315
 
310
316
  # Initialize and instrument only the enabled instrumentors
@@ -0,0 +1,50 @@
1
+ # pylint: disable=useless-return, bad-staticmethod-argument, disable=duplicate-code
2
+ """Initializer of Auto Instrumentation of CrewAI Functions"""
3
+
4
+ from typing import Collection
5
+ import importlib.metadata
6
+ from opentelemetry.instrumentation.instrumentor import BaseInstrumentor
7
+ from wrapt import wrap_function_wrapper
8
+
9
+ from openlit.instrumentation.crewai.crewai import (
10
+ crew_wrap
11
+ )
12
+
13
+ _instruments = ("crewai >= 0.80.0",)
14
+
15
+ class CrewAIInstrumentor(BaseInstrumentor):
16
+ """
17
+ An instrumentor for CrewAI's client library.
18
+ """
19
+
20
+ def instrumentation_dependencies(self) -> Collection[str]:
21
+ return _instruments
22
+
23
+ def _instrument(self, **kwargs):
24
+ application_name = kwargs.get("application_name", "default_application")
25
+ environment = kwargs.get("environment", "default_environment")
26
+ tracer = kwargs.get("tracer")
27
+ metrics = kwargs.get("metrics_dict")
28
+ pricing_info = kwargs.get("pricing_info", {})
29
+ trace_content = kwargs.get("trace_content", False)
30
+ disable_metrics = kwargs.get("disable_metrics")
31
+ version = importlib.metadata.version("crewai")
32
+
33
+ wrap_function_wrapper(
34
+ "crewai.agent",
35
+ "Agent.execute_task",
36
+ crew_wrap("crewai.agent_execute_task", version, environment, application_name,
37
+ tracer, pricing_info, trace_content, metrics, disable_metrics),
38
+ )
39
+
40
+ wrap_function_wrapper(
41
+ "crewai.task",
42
+ "Task._execute_core",
43
+ crew_wrap("crewai.task_execute_core", version, environment, application_name,
44
+ tracer, pricing_info, trace_content, metrics, disable_metrics),
45
+ )
46
+
47
+
48
+ def _uninstrument(self, **kwargs):
49
+ # Proper uninstrumentation logic to revert patched methods
50
+ pass
@@ -0,0 +1,149 @@
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
+ import json
8
+ from opentelemetry.trace import SpanKind, Status, StatusCode
9
+ from opentelemetry.sdk.resources import TELEMETRY_SDK_NAME
10
+ from openlit.__helpers import (
11
+ handle_exception,
12
+ )
13
+ from openlit.semcov import SemanticConvetion
14
+
15
+ # Initialize logger for logging potential issues and operations
16
+ logger = logging.getLogger(__name__)
17
+
18
+ def _parse_tools(tools):
19
+ result = []
20
+ for tool in tools:
21
+ res = {}
22
+ if hasattr(tool, "name") and tool.name is not None:
23
+ res["name"] = tool.name
24
+ if hasattr(tool, "description") and tool.description is not None:
25
+ res["description"] = tool.description
26
+ if res:
27
+ result.append(res)
28
+ return json.dumps(result)
29
+
30
+ def crew_wrap(gen_ai_endpoint, version, environment, application_name,
31
+ tracer, pricing_info, trace_content, metrics, disable_metrics):
32
+ """
33
+ Generates a telemetry wrapper for chat completions to collect metrics.
34
+
35
+ Args:
36
+ gen_ai_endpoint: Endpoint identifier for logging and tracing.
37
+ version: Version of the monitoring package.
38
+ environment: Deployment environment (e.g., production, staging).
39
+ application_name: Name of the application using the OpenAI API.
40
+ tracer: OpenTelemetry tracer for creating spans.
41
+ pricing_info: Information used for calculating the cost of OpenAI usage.
42
+ trace_content: Flag indicating whether to trace the actual content.
43
+
44
+ Returns:
45
+ A function that wraps the chat completions method to add telemetry.
46
+ """
47
+
48
+ def wrapper(wrapped, instance, args, kwargs):
49
+ """
50
+ Wraps the 'chat.completions' API call to add telemetry.
51
+
52
+ This collects metrics such as execution time, cost, and token usage, and handles errors
53
+ gracefully, adding details to the trace for observability.
54
+
55
+ Args:
56
+ wrapped: The original 'chat.completions' method to be wrapped.
57
+ instance: The instance of the class where the original method is defined.
58
+ args: Positional arguments for the 'chat.completions' method.
59
+ kwargs: Keyword arguments for the 'chat.completions' method.
60
+
61
+ Returns:
62
+ The response from the original 'chat.completions' method.
63
+ """
64
+
65
+ # pylint: disable=line-too-long
66
+ with tracer.start_as_current_span(gen_ai_endpoint, kind= SpanKind.CLIENT) as span:
67
+ response = wrapped(*args, **kwargs)
68
+
69
+ try:
70
+ # Set base span attribues
71
+ span.set_attribute(TELEMETRY_SDK_NAME, "openlit")
72
+ span.set_attribute(SemanticConvetion.GEN_AI_SYSTEM,
73
+ SemanticConvetion.GEN_AI_SYSTEM_OPENAI)
74
+ span.set_attribute(SemanticConvetion.GEN_AI_TYPE,
75
+ SemanticConvetion.GEN_AI_TYPE_CHAT)
76
+ span.set_attribute(SemanticConvetion.GEN_AI_ENDPOINT,
77
+ gen_ai_endpoint)
78
+
79
+ instance_class = instance.__class__.__name__
80
+
81
+ if instance_class == "Task":
82
+ task = {}
83
+ for key, value in instance.__dict__.items():
84
+ if value is None:
85
+ continue
86
+ if key == "tools":
87
+ value = _parse_tools(value)
88
+ task[key] = value
89
+ elif key == "agent":
90
+ task[key] = value.role
91
+ else:
92
+ task[key] = str(value)
93
+
94
+ span.set_attribute(SemanticConvetion.GEN_AI_AGENT_TASK_ID,
95
+ task.get('id', ''))
96
+ span.set_attribute(SemanticConvetion.GEN_AI_AGENT_TASK,
97
+ task.get('description', ''))
98
+ span.set_attribute(SemanticConvetion.GEN_AI_AGENT_EXPECTED_OUTPUT,
99
+ task.get('expected_output', ''))
100
+ span.set_attribute(SemanticConvetion.GEN_AI_AGENT_ACTUAL_OUTPUT,
101
+ task.get('output', ''))
102
+ span.set_attribute(SemanticConvetion.GEN_AI_AGENT_HUMAN_INPUT,
103
+ task.get('human_input', ''))
104
+ span.set_attribute(SemanticConvetion.GEN_AI_AGENT_TASK_ASSOCIATION,
105
+ str(task.get('processed_by_agents', '')))
106
+
107
+ elif instance_class == "Agent":
108
+ agent = {}
109
+ for key, value in instance.__dict__.items():
110
+ if key == "tools":
111
+ value = _parse_tools(value)
112
+ if value is None:
113
+ continue
114
+ agent[key] = str(value)
115
+
116
+ span.set_attribute(SemanticConvetion.GEN_AI_AGENT_ID,
117
+ agent.get('id', ''))
118
+ span.set_attribute(SemanticConvetion.GEN_AI_AGENT_ROLE,
119
+ agent.get('role', ''))
120
+ span.set_attribute(SemanticConvetion.GEN_AI_AGENT_GOAL,
121
+ agent.get('goal', ''))
122
+ span.set_attribute(SemanticConvetion.GEN_AI_AGENT_CONTEXT,
123
+ agent.get('backstory', ''))
124
+ span.set_attribute(SemanticConvetion.GEN_AI_AGENT_ENABLE_CACHE,
125
+ agent.get('cache', ''))
126
+ span.set_attribute(SemanticConvetion.GEN_AI_AGENT_ALLOW_DELEGATION,
127
+ agent.get('allow_delegation', ''))
128
+ span.set_attribute(SemanticConvetion.GEN_AI_AGENT_ALLOW_CODE_EXECUTION,
129
+ agent.get('allow_code_execution', ''))
130
+ span.set_attribute(SemanticConvetion.GEN_AI_AGENT_MAX_RETRY_LIMIT,
131
+ agent.get('max_retry_limit', ''))
132
+ span.set_attribute(SemanticConvetion.GEN_AI_AGENT_TOOLS,
133
+ str(agent.get('tools', '')))
134
+ span.set_attribute(SemanticConvetion.GEN_AI_AGENT_TOOL_RESULTS,
135
+ str(agent.get('tools_results', '')))
136
+
137
+ span.set_status(Status(StatusCode.OK))
138
+
139
+ # Return original response
140
+ return response
141
+
142
+ except Exception as e:
143
+ handle_exception(span, e)
144
+ logger.error("Error in trace creation: %s", e)
145
+
146
+ # Return original response
147
+ return response
148
+
149
+ return wrapper
@@ -0,0 +1,54 @@
1
+ # pylint: disable=useless-return, bad-staticmethod-argument, disable=duplicate-code
2
+ """Initializer of Auto Instrumentation of LiteLLM Functions"""
3
+
4
+ from typing import Collection
5
+ import importlib.metadata
6
+ from opentelemetry.instrumentation.instrumentor import BaseInstrumentor
7
+ from wrapt import wrap_function_wrapper
8
+
9
+ from openlit.instrumentation.litellm.litellm import (
10
+ completion
11
+ )
12
+ from openlit.instrumentation.litellm.async_litellm import (
13
+ acompletion
14
+ )
15
+
16
+ _instruments = ("litellm >= 1.52.6",)
17
+
18
+ class LiteLLMInstrumentor(BaseInstrumentor):
19
+ """
20
+ An instrumentor for LiteLLM's client library.
21
+ """
22
+
23
+ def instrumentation_dependencies(self) -> Collection[str]:
24
+ return _instruments
25
+
26
+ def _instrument(self, **kwargs):
27
+ application_name = kwargs.get("application_name", "default_application")
28
+ environment = kwargs.get("environment", "default_environment")
29
+ tracer = kwargs.get("tracer")
30
+ metrics = kwargs.get("metrics_dict")
31
+ pricing_info = kwargs.get("pricing_info", {})
32
+ trace_content = kwargs.get("trace_content", False)
33
+ disable_metrics = kwargs.get("disable_metrics")
34
+ version = importlib.metadata.version("litellm")
35
+
36
+ # completion
37
+ wrap_function_wrapper(
38
+ "litellm",
39
+ "completion",
40
+ completion("litellm.completion", version, environment, application_name,
41
+ tracer, pricing_info, trace_content, metrics, disable_metrics),
42
+ )
43
+
44
+ wrap_function_wrapper(
45
+ "litellm",
46
+ "acompletion",
47
+ acompletion("litellm.completion", version, environment, application_name,
48
+ tracer, pricing_info, trace_content, metrics, disable_metrics),
49
+ )
50
+
51
+
52
+ def _uninstrument(self, **kwargs):
53
+ # Proper uninstrumentation logic to revert patched methods
54
+ pass
@@ -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 acompletion(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 TracedAsyncStream:
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
+ async def __aenter__(self):
66
+ await self.__wrapped__.__aenter__()
67
+ return self
68
+
69
+ async def __aexit__(self, exc_type, exc_value, traceback):
70
+ await self.__wrapped__.__aexit__(exc_type, exc_value, traceback)
71
+
72
+ def __aiter__(self):
73
+ return self
74
+
75
+ async def __getattr__(self, name):
76
+ """Delegate attribute access to the wrapped object."""
77
+ return getattr(await self.__wrapped__, name)
78
+
79
+ async def __anext__(self):
80
+ try:
81
+ chunk = await self.__wrapped__.__anext__()
82
+ chunked = response_as_dict(chunk)
83
+ # Collect message IDs and aggregated response from events
84
+ if (len(chunked.get('choices')) > 0 and ('delta' in chunked.get('choices')[0] and
85
+ 'content' in chunked.get('choices')[0].get('delta'))):
86
+
87
+ content = chunked.get('choices')[0].get('delta').get('content')
88
+ if content:
89
+ self._llmresponse += content
90
+ self._response_id = chunked.get('id')
91
+ return chunk
92
+ except StopAsyncIteration:
93
+ # Handling exception ensure observability without disrupting operation
94
+ try:
95
+ # Format 'messages' into a single string
96
+ message_prompt = self._kwargs.get("messages", "")
97
+ formatted_messages = []
98
+ for message in message_prompt:
99
+ role = message["role"]
100
+ content = message["content"]
101
+
102
+ if isinstance(content, list):
103
+ content_str = ", ".join(
104
+ # pylint: disable=line-too-long
105
+ f'{item["type"]}: {item["text"] if "text" in item else item["image_url"]}'
106
+ if "type" in item else f'text: {item["text"]}'
107
+ for item in content
108
+ )
109
+ formatted_messages.append(f"{role}: {content_str}")
110
+ else:
111
+ formatted_messages.append(f"{role}: {content}")
112
+ prompt = "\n".join(formatted_messages)
113
+
114
+ # Calculate tokens using input prompt and aggregated response
115
+ prompt_tokens = openai_tokens(prompt,
116
+ self._kwargs.get("model", "gpt-3.5-turbo"))
117
+ completion_tokens = openai_tokens(self._llmresponse,
118
+ self._kwargs.get("model", "gpt-3.5-turbo"))
119
+
120
+ # Calculate cost of the operation
121
+ cost = get_chat_model_cost(self._kwargs.get("model", "gpt-3.5-turbo"),
122
+ pricing_info, prompt_tokens,
123
+ completion_tokens)
124
+
125
+ # Set Span attributes
126
+ self._span.set_attribute(TELEMETRY_SDK_NAME, "openlit")
127
+ self._span.set_attribute(SemanticConvetion.GEN_AI_SYSTEM,
128
+ SemanticConvetion.GEN_AI_SYSTEM_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
+ async def wrapper(wrapped, instance, args, kwargs):
213
+ """
214
+ Wraps the 'chat.completions' API call to add telemetry.
215
+
216
+ This collects metrics such as execution time, cost, and token usage, and handles errors
217
+ gracefully, adding details to the trace for observability.
218
+
219
+ Args:
220
+ wrapped: The original 'chat.completions' method to be wrapped.
221
+ instance: The instance of the class where the original method is defined.
222
+ args: Positional arguments for the 'chat.completions' method.
223
+ kwargs: Keyword arguments for the 'chat.completions' method.
224
+
225
+ Returns:
226
+ The response from the original 'chat.completions' method.
227
+ """
228
+
229
+ # Check if streaming is enabled for the API call
230
+ streaming = kwargs.get("stream", False)
231
+
232
+ # pylint: disable=no-else-return
233
+ if streaming:
234
+ # Special handling for streaming response to accommodate the nature of data flow
235
+ awaited_wrapped = await wrapped(*args, **kwargs)
236
+ span = tracer.start_span(gen_ai_endpoint, kind=SpanKind.CLIENT)
237
+
238
+ return TracedAsyncStream(awaited_wrapped, span, kwargs)
239
+
240
+ # Handling for non-streaming responses
241
+ else:
242
+ # pylint: disable=line-too-long
243
+ with tracer.start_as_current_span(gen_ai_endpoint, kind= SpanKind.CLIENT) as span:
244
+ response = await wrapped(*args, **kwargs)
245
+
246
+ response_dict = response_as_dict(response)
247
+
248
+ try:
249
+ # Format 'messages' into a single string
250
+ message_prompt = kwargs.get("messages", "")
251
+ formatted_messages = []
252
+ for message in message_prompt:
253
+ role = message["role"]
254
+ content = message["content"]
255
+
256
+ if isinstance(content, list):
257
+ content_str = ", ".join(
258
+ # pylint: disable=line-too-long
259
+ f'{item["type"]}: {item["text"] if "text" in item else item["image_url"]}'
260
+ if "type" in item else f'text: {item["text"]}'
261
+ for item in content
262
+ )
263
+ formatted_messages.append(f"{role}: {content_str}")
264
+ else:
265
+ formatted_messages.append(f"{role}: {content}")
266
+ prompt = "\n".join(formatted_messages)
267
+
268
+ # Set base span attribues
269
+ span.set_attribute(TELEMETRY_SDK_NAME, "openlit")
270
+ span.set_attribute(SemanticConvetion.GEN_AI_SYSTEM,
271
+ SemanticConvetion.GEN_AI_SYSTEM_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
@@ -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
@@ -468,8 +468,8 @@ def async_embedding(gen_ai_endpoint, version, environment, application_name,
468
468
  kwargs.get("model", "text-embedding-ada-002"))
469
469
  span.set_attribute(SemanticConvetion.GEN_AI_REQUEST_EMBEDDING_FORMAT,
470
470
  kwargs.get("encoding_format", "float"))
471
- span.set_attribute(SemanticConvetion.GEN_AI_REQUEST_EMBEDDING_DIMENSION,
472
- kwargs.get("dimensions", ""))
471
+ # span.set_attribute(SemanticConvetion.GEN_AI_REQUEST_EMBEDDING_DIMENSION,
472
+ # kwargs.get("dimensions", "null"))
473
473
  span.set_attribute(SemanticConvetion.GEN_AI_REQUEST_USER,
474
474
  kwargs.get("user", ""))
475
475
  span.set_attribute(SemanticConvetion.GEN_AI_USAGE_PROMPT_TOKENS,
@@ -468,8 +468,8 @@ def embedding(gen_ai_endpoint, version, environment, application_name,
468
468
  kwargs.get("model", "text-embedding-ada-002"))
469
469
  span.set_attribute(SemanticConvetion.GEN_AI_REQUEST_EMBEDDING_FORMAT,
470
470
  kwargs.get("encoding_format", "float"))
471
- span.set_attribute(SemanticConvetion.GEN_AI_REQUEST_EMBEDDING_DIMENSION,
472
- kwargs.get("dimensions", ""))
471
+ # span.set_attribute(SemanticConvetion.GEN_AI_REQUEST_EMBEDDING_DIMENSION,
472
+ # kwargs.get("dimensions", "null"))
473
473
  span.set_attribute(SemanticConvetion.GEN_AI_REQUEST_USER,
474
474
  kwargs.get("user", ""))
475
475
  span.set_attribute(SemanticConvetion.GEN_AI_USAGE_PROMPT_TOKENS,
@@ -154,6 +154,24 @@ class SemanticConvetion:
154
154
  DB_SYSTEM_QDRANT = "qdrant"
155
155
  DB_SYSTEM_MILVUS = "milvus"
156
156
 
157
+ # Agents
158
+ GEN_AI_AGENT_ID = "gen_ai.agent.id"
159
+ GEN_AI_AGENT_TASK_ID = "gen_ai.agent.task.id"
160
+ GEN_AI_AGENT_ROLE = "gen_ai.agent.role"
161
+ GEN_AI_AGENT_GOAL = "gen_ai.agent.goal"
162
+ GEN_AI_AGENT_CONTEXT = "gen_ai.agent.context"
163
+ GEN_AI_AGENT_ENABLE_CACHE = "gen_ai.agent.enable_cache"
164
+ GEN_AI_AGENT_ALLOW_DELEGATION = "gen_ai.agent.allow_delegation"
165
+ GEN_AI_AGENT_ALLOW_CODE_EXECUTION = "gen_ai.agent.allow_code_execution"
166
+ GEN_AI_AGENT_MAX_RETRY_LIMIT = "gen_ai.agent.max_retry_limit"
167
+ GEN_AI_AGENT_TOOLS = "gen_ai.agent.tools"
168
+ GEN_AI_AGENT_TOOL_RESULTS = "gen_ai.agent.tool_results"
169
+ GEN_AI_AGENT_TASK = "gen_ai.agent.task"
170
+ GEN_AI_AGENT_EXPECTED_OUTPUT = "gen_ai.agent.expected_output"
171
+ GEN_AI_AGENT_ACTUAL_OUTPUT = "gen_ai.agent.actual_output"
172
+ GEN_AI_AGENT_HUMAN_INPUT = "gen_ai.agent.human_input"
173
+ GEN_AI_AGENT_TASK_ASSOCIATION = "gen_ai.agent.task_associations"
174
+
157
175
  # GPU
158
176
  GPU_INDEX = "gpu.index"
159
177
  GPU_UUID = "gpu.uuid"
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.1
2
2
  Name: openlit
3
- Version: 1.29.4
3
+ Version: 1.30.0
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
@@ -63,16 +63,16 @@ This project proudly follows and maintains the [Semantic Conventions](https://gi
63
63
 
64
64
  ## Auto Instrumentation Capabilities
65
65
 
66
- | LLMs | Vector DBs | Frameworks | GPUs |
67
- |--------------------------------------------------------------------------|----------------------------------------------|----------------------------------------------|---------------|
68
- | [✅ OpenAI](https://docs.openlit.io/latest/integrations/openai) | [✅ ChromaDB](https://docs.openlit.io/latest/integrations/chromadb) | [✅ Langchain](https://docs.openlit.io/latest/integrations/langchain) | [✅ NVIDIA](https://docs.openlit.io/latest/integrations/nvidia-gpu) |
69
- | [✅ Ollama](https://docs.openlit.io/latest/integrations/ollama) | [✅ Pinecone](https://docs.openlit.io/latest/integrations/pinecone) | [✅ LiteLLM](https://docs.openlit.io/latest/integrations/litellm) | [✅ AMD](#) |
70
- | [✅ Anthropic](https://docs.openlit.io/latest/integrations/anthropic) | [✅ Qdrant](https://docs.openlit.io/latest/integrations/qdrant) | [✅ LlamaIndex](https://docs.openlit.io/latest/integrations/llama-index) | |
71
- | [✅ GPT4All](https://docs.openlit.io/latest/integrations/gpt4all) | [✅ Milvus](https://docs.openlit.io/latest/integrations/milvus) | [✅ Haystack](https://docs.openlit.io/latest/integrations/haystack) | |
72
- | [✅ Cohere](https://docs.openlit.io/latest/integrations/cohere) | | [✅ EmbedChain](https://docs.openlit.io/latest/integrations/embedchain) | |
73
- | [✅ Mistral](https://docs.openlit.io/latest/integrations/mistral) | | [✅ Guardrails](https://docs.openlit.io/latest/integrations/guardrails) | |
74
- | [✅ Azure OpenAI](https://docs.openlit.io/latest/integrations/azure-openai) | | | |
75
- | [✅ Azure AI Inference](https://docs.openlit.io/latest/integrations/azure-ai-inference) | | | |
66
+ | LLMs | Vector DBs | Frameworks | GPUs |
67
+ |--------------------------------------------------------------------------|----------------------------------------------|-------------------------------------------------|---------------|
68
+ | [✅ OpenAI](https://docs.openlit.io/latest/integrations/openai) | [✅ ChromaDB](https://docs.openlit.io/latest/integrations/chromadb) | [✅ Langchain](https://docs.openlit.io/latest/integrations/langchain) | [✅ NVIDIA](https://docs.openlit.io/latest/integrations/nvidia-gpu) |
69
+ | [✅ Ollama](https://docs.openlit.io/latest/integrations/ollama) | [✅ Pinecone](https://docs.openlit.io/latest/integrations/pinecone) | [✅ LiteLLM](https://docs.openlit.io/latest/integrations/litellm) | [✅ AMD](#) |
70
+ | [✅ Anthropic](https://docs.openlit.io/latest/integrations/anthropic) | [✅ Qdrant](https://docs.openlit.io/latest/integrations/qdrant) | [✅ LlamaIndex](https://docs.openlit.io/latest/integrations/llama-index) | |
71
+ | [✅ GPT4All](https://docs.openlit.io/latest/integrations/gpt4all) | [✅ Milvus](https://docs.openlit.io/latest/integrations/milvus) | [✅ Haystack](https://docs.openlit.io/latest/integrations/haystack) | |
72
+ | [✅ Cohere](https://docs.openlit.io/latest/integrations/cohere) | | [✅ EmbedChain](https://docs.openlit.io/latest/integrations/embedchain) | |
73
+ | [✅ Mistral](https://docs.openlit.io/latest/integrations/mistral) | | [✅ Guardrails](https://docs.openlit.io/latest/integrations/guardrails) | |
74
+ | [✅ Azure OpenAI](https://docs.openlit.io/latest/integrations/azure-openai) | | [✅ CrewAI](https://docs.openlit.io/latest/integrations/crewai) | |
75
+ | [✅ Azure AI Inference](https://docs.openlit.io/latest/integrations/azure-ai-inference) | |
76
76
  | [✅ GitHub AI Models](https://docs.openlit.io/latest/integrations/github-models) | | | |
77
77
  | [✅ HuggingFace Transformers](https://docs.openlit.io/latest/integrations/huggingface) | | | |
78
78
  | [✅ Amazon Bedrock](https://docs.openlit.io/latest/integrations/bedrock) | | | |
@@ -1,5 +1,5 @@
1
1
  openlit/__helpers.py,sha256=2OkGKOdsd9Hc011WxR70OqDlO6c4mZcu6McGuW1uAdA,6316
2
- openlit/__init__.py,sha256=2tsUq6WYudGEYaEOKpRv4absxS-4ElTbbvV_J7QyFKg,19380
2
+ openlit/__init__.py,sha256=cUWwxNAwJvklVpE1LV929JWipsng0KLukcY0BUGFhJM,19654
3
3
  openlit/evals/__init__.py,sha256=nJe99nuLo1b5rf7pt9U9BCdSDedzbVi2Fj96cgl7msM,380
4
4
  openlit/evals/all.py,sha256=oWrue3PotE-rB5WePG3MRYSA-ro6WivkclSHjYlAqGs,7154
5
5
  openlit/evals/bias_detection.py,sha256=mCdsfK7x1vX7S3psC3g641IMlZ-7df3h-V6eiICj5N8,8154
@@ -24,6 +24,8 @@ openlit/instrumentation/chroma/__init__.py,sha256=61lFpHlUEQUobsUJZHXdvOViKwsOH8
24
24
  openlit/instrumentation/chroma/chroma.py,sha256=E80j_41UeZi8RzTsHbpvi1izOA_n-0-3_VdrA68AJPA,10531
25
25
  openlit/instrumentation/cohere/__init__.py,sha256=PC5T1qIg9pwLNocBP_WjG5B_6p_z019s8quk_fNLAMs,1920
26
26
  openlit/instrumentation/cohere/cohere.py,sha256=62-P2K39v6pIJme6vTVViLJ9PP8q_UWkTv2l3Wa2gHA,21217
27
+ openlit/instrumentation/crewai/__init__.py,sha256=cETkkwnKYEMAKlMrHbZ9-RvcRUPYaSNqNIhy2-vCDK8,1794
28
+ openlit/instrumentation/crewai/crewai.py,sha256=xiyWqYv2euyIhjuw4kM_jacH4MuVTlac6lCqzjnAbmM,6914
27
29
  openlit/instrumentation/elevenlabs/__init__.py,sha256=BZjAe-kzFJpKxT0tKksXVfZgirvgEp8qM3SfegWU5co,2631
28
30
  openlit/instrumentation/elevenlabs/async_elevenlabs.py,sha256=yMYACh95SFr5EYklKnXw2DrPFa3iIgM4qQMWjO1itMU,5690
29
31
  openlit/instrumentation/elevenlabs/elevenlabs.py,sha256=mFnD7sgT47OxaXJz0Vc1nrNjXEpcGQDj5run3gA48Lw,6089
@@ -42,6 +44,9 @@ openlit/instrumentation/haystack/__init__.py,sha256=QK6XxxZUHX8vMv2Crk7rNBOc64iO
42
44
  openlit/instrumentation/haystack/haystack.py,sha256=oQIZiDhdp3gnJnhYQ1OouJMc9YT0pQ-_31cmNuopa68,3891
43
45
  openlit/instrumentation/langchain/__init__.py,sha256=0AI2Dnqw81IcJw3jM--gGkv_HRh2GtosOGJjvOpw7Zk,3431
44
46
  openlit/instrumentation/langchain/langchain.py,sha256=g3HDKPq498KitHuQxxfQzvRq9MKAZaR0jStQYTLx_-M,35592
47
+ openlit/instrumentation/litellm/__init__.py,sha256=XV3PxqhlZYoJ3FbVr9MiWPogrE3_HOAv-BvOObylU4M,1866
48
+ openlit/instrumentation/litellm/async_litellm.py,sha256=wsi9GLfp4h4gu2128YMmkgBlnPqPvG5GUdHVddZfPkI,21919
49
+ openlit/instrumentation/litellm/litellm.py,sha256=ayKFyxX8hu9P-FdA-Nn4cf-ewXJD1FCygv3ota35Xe4,21832
45
50
  openlit/instrumentation/llamaindex/__init__.py,sha256=vPtK65G6b-TwJERowVRUVl7f_nBSlFdwPBtpg8dOGos,1977
46
51
  openlit/instrumentation/llamaindex/llamaindex.py,sha256=uiIigbwhonSbJWA7LpgOVI1R4kxxPODS1K5wyHIQ4hM,4048
47
52
  openlit/instrumentation/milvus/__init__.py,sha256=qi1yfmMrvkDtnrN_6toW8qC9BRL78bq7ayWpObJ8Bq4,2961
@@ -54,9 +59,9 @@ openlit/instrumentation/ollama/async_ollama.py,sha256=7lbikD-I9k8VL63idqj3VMEfiE
54
59
  openlit/instrumentation/ollama/ollama.py,sha256=lBt1d3rFnF1tFbfdOccwjEafHnmTAUGsiOKSHku6Fkw,31277
55
60
  openlit/instrumentation/openai/__init__.py,sha256=AZ2cPr3TMKkgGdMl_yXMeSi7bWhtmMqOW1iHdzHHGHA,16265
56
61
  openlit/instrumentation/openai/async_azure_openai.py,sha256=XbST1UE_zXzNL6RX2XwCsK_a6IhG9PHVTMKBjGrUcB0,48961
57
- openlit/instrumentation/openai/async_openai.py,sha256=fsLW4K3OW6meM2cQN-6ClmWUGBG_hIsLR8tmP9yv7tQ,49977
62
+ openlit/instrumentation/openai/async_openai.py,sha256=IYJAHXxG7O7jxDL3OYNpT4ybmjUoMXTKXjjg1ns-HMg,49985
58
63
  openlit/instrumentation/openai/azure_openai.py,sha256=dZUc5MtCwg_sZJWiruG6exYGhPAm-339sqs3sKZNRPU,48761
59
- openlit/instrumentation/openai/openai.py,sha256=XoQPiHiTpfIaTqKupZ99iXf9Y7OUM-9KXUy-dwJymwg,49806
64
+ openlit/instrumentation/openai/openai.py,sha256=iJA8xaqlydfltHogoTsClIVZDJxO-yGRMSRppNYJ8iM,49814
60
65
  openlit/instrumentation/pinecone/__init__.py,sha256=Mv9bElqNs07_JQkYyNnO0wOM3hdbprmw7sttdMeKC7g,2526
61
66
  openlit/instrumentation/pinecone/pinecone.py,sha256=0EhLmtOuvwWVvAKh3e56wyd8wzQq1oaLOmF15SVHxVE,8765
62
67
  openlit/instrumentation/qdrant/__init__.py,sha256=GMlZgRBKoQMgrL4cFbAKwytfdTHLzJEIuTQMxp0uZO0,8940
@@ -71,8 +76,8 @@ openlit/instrumentation/vllm/__init__.py,sha256=OVWalQ1dXvip1DUsjUGaHX4J-2FrSp-T
71
76
  openlit/instrumentation/vllm/vllm.py,sha256=lDzM7F5pgxvh8nKL0dcKB4TD0Mc9wXOWeXOsOGN7Wd8,6527
72
77
  openlit/otel/metrics.py,sha256=FYAk4eBAmNtFKUIp4hbRbpdq4LME6MapyCQOIeuhmEg,4337
73
78
  openlit/otel/tracing.py,sha256=2kSj7n7uXSkRegcGFDC8IbnDOxqWTA8dGODs__Yn_yA,3719
74
- openlit/semcov/__init__.py,sha256=xPsw1aPonDSGYVuga-ZdoGt4yyA16wNFi5AEc7_xIrQ,8114
75
- openlit-1.29.4.dist-info/LICENSE,sha256=xx0jnfkXJvxRnG63LTGOxlggYnIysveWIZ6H3PNdCrQ,11357
76
- openlit-1.29.4.dist-info/METADATA,sha256=2sTJQzyPiNcouwBuTVsrX-Bu1aeWUd23c7mg33Gscvg,20806
77
- openlit-1.29.4.dist-info/WHEEL,sha256=Nq82e9rUAnEjt98J6MlVmMCZb-t9cYE2Ir1kpBmnWfs,88
78
- openlit-1.29.4.dist-info/RECORD,,
79
+ openlit/semcov/__init__.py,sha256=FhaEFY7nStofZsdwHPtZbnNDCAs3i0NMvp80R_HEBAc,9031
80
+ openlit-1.30.0.dist-info/LICENSE,sha256=xx0jnfkXJvxRnG63LTGOxlggYnIysveWIZ6H3PNdCrQ,11357
81
+ openlit-1.30.0.dist-info/METADATA,sha256=9jdPX05oWaVYZ5lMtfkR4Yyzbt4zYC_ZUZza_MBxseA,20841
82
+ openlit-1.30.0.dist-info/WHEEL,sha256=Nq82e9rUAnEjt98J6MlVmMCZb-t9cYE2Ir1kpBmnWfs,88
83
+ openlit-1.30.0.dist-info/RECORD,,