openlit 1.29.4__py3-none-any.whl → 1.30.1__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 CrewAI Agent.
40
+ tracer: OpenTelemetry tracer for creating spans.
41
+ pricing_info: Information used for calculating the cost of CrewAI 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_CREWAI)
74
+ span.set_attribute(SemanticConvetion.GEN_AI_TYPE,
75
+ SemanticConvetion.GEN_AI_TYPE_AGENT)
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,406 @@
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 LiteLLM SDK.
30
+ tracer: OpenTelemetry tracer for creating spans.
31
+ pricing_info: Information used for calculating the cost of LiteLLM 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
+
42
+ This class implements the '__aiter__' and '__anext__' methods that
43
+ handle asynchronous streaming responses.
44
+
45
+ This class also implements '__aenter__' and '__aexit__' methods that
46
+ handle asynchronous context management protocol.
47
+ """
48
+ def __init__(
49
+ self,
50
+ wrapped,
51
+ span,
52
+ kwargs,
53
+ **args,
54
+ ):
55
+ self.__wrapped__ = wrapped
56
+ self._span = span
57
+ # Placeholder for aggregating streaming response
58
+ self._llmresponse = ""
59
+ self._response_id = ""
60
+
61
+ self._args = args
62
+ self._kwargs = kwargs
63
+
64
+ async def __aenter__(self):
65
+ await self.__wrapped__.__aenter__()
66
+ return self
67
+
68
+ async def __aexit__(self, exc_type, exc_value, traceback):
69
+ await self.__wrapped__.__aexit__(exc_type, exc_value, traceback)
70
+
71
+ def __aiter__(self):
72
+ return self
73
+
74
+ async def __getattr__(self, name):
75
+ """Delegate attribute access to the wrapped object."""
76
+ return getattr(await self.__wrapped__, name)
77
+
78
+ async def __anext__(self):
79
+ try:
80
+ chunk = await self.__wrapped__.__anext__()
81
+ chunked = response_as_dict(chunk)
82
+ # Collect message IDs and aggregated response from events
83
+ if (len(chunked.get('choices')) > 0 and ('delta' in chunked.get('choices')[0] and
84
+ 'content' in chunked.get('choices')[0].get('delta'))):
85
+
86
+ content = chunked.get('choices')[0].get('delta').get('content')
87
+ if content:
88
+ self._llmresponse += content
89
+ self._response_id = chunked.get('id')
90
+ return chunk
91
+ except StopAsyncIteration:
92
+ # Handling exception ensure observability without disrupting operation
93
+ try:
94
+ # Format 'messages' into a single string
95
+ message_prompt = self._kwargs.get("messages", "")
96
+ formatted_messages = []
97
+ for message in message_prompt:
98
+ role = message["role"]
99
+ content = message["content"]
100
+
101
+ if isinstance(content, list):
102
+ content_str = ", ".join(
103
+ # pylint: disable=line-too-long
104
+ f'{item["type"]}: {item["text"] if "text" in item else item["image_url"]}'
105
+ if "type" in item else f'text: {item["text"]}'
106
+ for item in content
107
+ )
108
+ formatted_messages.append(f"{role}: {content_str}")
109
+ else:
110
+ formatted_messages.append(f"{role}: {content}")
111
+ prompt = "\n".join(formatted_messages)
112
+
113
+ # Calculate tokens using input prompt and aggregated response
114
+ prompt_tokens = openai_tokens(prompt,
115
+ self._kwargs.get("model", "gpt-3.5-turbo"))
116
+ completion_tokens = openai_tokens(self._llmresponse,
117
+ self._kwargs.get("model", "gpt-3.5-turbo"))
118
+
119
+ # Calculate cost of the operation
120
+ cost = get_chat_model_cost(self._kwargs.get("model", "gpt-3.5-turbo"),
121
+ pricing_info, prompt_tokens,
122
+ completion_tokens)
123
+
124
+ # Set Span attributes
125
+ self._span.set_attribute(TELEMETRY_SDK_NAME, "openlit")
126
+ self._span.set_attribute(SemanticConvetion.GEN_AI_SYSTEM,
127
+ SemanticConvetion.GEN_AI_SYSTEM_LITELLM)
128
+ self._span.set_attribute(SemanticConvetion.GEN_AI_TYPE,
129
+ SemanticConvetion.GEN_AI_TYPE_CHAT)
130
+ self._span.set_attribute(SemanticConvetion.GEN_AI_ENDPOINT,
131
+ gen_ai_endpoint)
132
+ self._span.set_attribute(SemanticConvetion.GEN_AI_RESPONSE_ID,
133
+ self._response_id)
134
+ self._span.set_attribute(SemanticConvetion.GEN_AI_ENVIRONMENT,
135
+ environment)
136
+ self._span.set_attribute(SemanticConvetion.GEN_AI_APPLICATION_NAME,
137
+ application_name)
138
+ self._span.set_attribute(SemanticConvetion.GEN_AI_REQUEST_MODEL,
139
+ self._kwargs.get("model", "gpt-3.5-turbo"))
140
+ self._span.set_attribute(SemanticConvetion.GEN_AI_REQUEST_USER,
141
+ self._kwargs.get("user", ""))
142
+ self._span.set_attribute(SemanticConvetion.GEN_AI_REQUEST_TOP_P,
143
+ self._kwargs.get("top_p", 1.0))
144
+ self._span.set_attribute(SemanticConvetion.GEN_AI_REQUEST_MAX_TOKENS,
145
+ self._kwargs.get("max_tokens", -1))
146
+ self._span.set_attribute(SemanticConvetion.GEN_AI_REQUEST_TEMPERATURE,
147
+ self._kwargs.get("temperature", 1.0))
148
+ self._span.set_attribute(SemanticConvetion.GEN_AI_REQUEST_PRESENCE_PENALTY,
149
+ self._kwargs.get("presence_penalty", 0.0))
150
+ self._span.set_attribute(SemanticConvetion.GEN_AI_REQUEST_FREQUENCY_PENALTY,
151
+ self._kwargs.get("frequency_penalty", 0.0))
152
+ self._span.set_attribute(SemanticConvetion.GEN_AI_REQUEST_SEED,
153
+ self._kwargs.get("seed", ""))
154
+ self._span.set_attribute(SemanticConvetion.GEN_AI_REQUEST_IS_STREAM,
155
+ True)
156
+ self._span.set_attribute(SemanticConvetion.GEN_AI_USAGE_PROMPT_TOKENS,
157
+ prompt_tokens)
158
+ self._span.set_attribute(SemanticConvetion.GEN_AI_USAGE_COMPLETION_TOKENS,
159
+ completion_tokens)
160
+ self._span.set_attribute(SemanticConvetion.GEN_AI_USAGE_TOTAL_TOKENS,
161
+ prompt_tokens + completion_tokens)
162
+ self._span.set_attribute(SemanticConvetion.GEN_AI_USAGE_COST,
163
+ cost)
164
+ if trace_content:
165
+ self._span.add_event(
166
+ name=SemanticConvetion.GEN_AI_CONTENT_PROMPT_EVENT,
167
+ attributes={
168
+ SemanticConvetion.GEN_AI_CONTENT_PROMPT: prompt,
169
+ },
170
+ )
171
+ self._span.add_event(
172
+ name=SemanticConvetion.GEN_AI_CONTENT_COMPLETION_EVENT,
173
+ attributes={
174
+ SemanticConvetion.GEN_AI_CONTENT_COMPLETION: self._llmresponse,
175
+ },
176
+ )
177
+
178
+ self._span.set_status(Status(StatusCode.OK))
179
+
180
+ if disable_metrics is False:
181
+ attributes = {
182
+ TELEMETRY_SDK_NAME:
183
+ "openlit",
184
+ SemanticConvetion.GEN_AI_APPLICATION_NAME:
185
+ application_name,
186
+ SemanticConvetion.GEN_AI_SYSTEM:
187
+ SemanticConvetion.GEN_AI_SYSTEM_LITELLM,
188
+ SemanticConvetion.GEN_AI_ENVIRONMENT:
189
+ environment,
190
+ SemanticConvetion.GEN_AI_TYPE:
191
+ SemanticConvetion.GEN_AI_TYPE_CHAT,
192
+ SemanticConvetion.GEN_AI_REQUEST_MODEL:
193
+ self._kwargs.get("model", "gpt-3.5-turbo")
194
+ }
195
+
196
+ metrics["genai_requests"].add(1, attributes)
197
+ metrics["genai_total_tokens"].add(
198
+ prompt_tokens + completion_tokens, attributes
199
+ )
200
+ metrics["genai_completion_tokens"].add(completion_tokens, attributes)
201
+ metrics["genai_prompt_tokens"].add(prompt_tokens, attributes)
202
+ metrics["genai_cost"].record(cost, attributes)
203
+
204
+ except Exception as e:
205
+ handle_exception(self._span, e)
206
+ logger.error("Error in trace creation: %s", e)
207
+ finally:
208
+ self._span.end()
209
+ raise
210
+
211
+ async def wrapper(wrapped, instance, args, kwargs):
212
+ """
213
+ Wraps the 'chat.completions' API call to add telemetry.
214
+
215
+ This collects metrics such as execution time, cost, and token usage, and handles errors
216
+ gracefully, adding details to the trace for observability.
217
+
218
+ Args:
219
+ wrapped: The original 'chat.completions' method to be wrapped.
220
+ instance: The instance of the class where the original method is defined.
221
+ args: Positional arguments for the 'chat.completions' method.
222
+ kwargs: Keyword arguments for the 'chat.completions' method.
223
+
224
+ Returns:
225
+ The response from the original 'chat.completions' method.
226
+ """
227
+
228
+ # Check if streaming is enabled for the API call
229
+ streaming = kwargs.get("stream", False)
230
+
231
+ # pylint: disable=no-else-return
232
+ if streaming:
233
+ # Special handling for streaming response to accommodate the nature of data flow
234
+ awaited_wrapped = await wrapped(*args, **kwargs)
235
+ span = tracer.start_span(gen_ai_endpoint, kind=SpanKind.CLIENT)
236
+
237
+ return TracedAsyncStream(awaited_wrapped, span, kwargs)
238
+
239
+ # Handling for non-streaming responses
240
+ else:
241
+ # pylint: disable=line-too-long
242
+ with tracer.start_as_current_span(gen_ai_endpoint, kind= SpanKind.CLIENT) as span:
243
+ response = await wrapped(*args, **kwargs)
244
+
245
+ response_dict = response_as_dict(response)
246
+
247
+ try:
248
+ # Format 'messages' into a single string
249
+ message_prompt = kwargs.get("messages", "")
250
+ formatted_messages = []
251
+ for message in message_prompt:
252
+ role = message["role"]
253
+ content = message["content"]
254
+
255
+ if isinstance(content, list):
256
+ content_str = ", ".join(
257
+ # pylint: disable=line-too-long
258
+ f'{item["type"]}: {item["text"] if "text" in item else item["image_url"]}'
259
+ if "type" in item else f'text: {item["text"]}'
260
+ for item in content
261
+ )
262
+ formatted_messages.append(f"{role}: {content_str}")
263
+ else:
264
+ formatted_messages.append(f"{role}: {content}")
265
+ prompt = "\n".join(formatted_messages)
266
+
267
+ # Set base span attribues
268
+ span.set_attribute(TELEMETRY_SDK_NAME, "openlit")
269
+ span.set_attribute(SemanticConvetion.GEN_AI_SYSTEM,
270
+ SemanticConvetion.GEN_AI_SYSTEM_LITELLM)
271
+ span.set_attribute(SemanticConvetion.GEN_AI_TYPE,
272
+ SemanticConvetion.GEN_AI_TYPE_CHAT)
273
+ span.set_attribute(SemanticConvetion.GEN_AI_ENDPOINT,
274
+ gen_ai_endpoint)
275
+ span.set_attribute(SemanticConvetion.GEN_AI_RESPONSE_ID,
276
+ response_dict.get("id"))
277
+ span.set_attribute(SemanticConvetion.GEN_AI_ENVIRONMENT,
278
+ environment)
279
+ span.set_attribute(SemanticConvetion.GEN_AI_APPLICATION_NAME,
280
+ application_name)
281
+ span.set_attribute(SemanticConvetion.GEN_AI_REQUEST_MODEL,
282
+ kwargs.get("model", "gpt-3.5-turbo"))
283
+ span.set_attribute(SemanticConvetion.GEN_AI_REQUEST_TOP_P,
284
+ kwargs.get("top_p", 1.0))
285
+ span.set_attribute(SemanticConvetion.GEN_AI_REQUEST_MAX_TOKENS,
286
+ kwargs.get("max_tokens", -1))
287
+ span.set_attribute(SemanticConvetion.GEN_AI_REQUEST_USER,
288
+ kwargs.get("user", ""))
289
+ span.set_attribute(SemanticConvetion.GEN_AI_REQUEST_TEMPERATURE,
290
+ kwargs.get("temperature", 1.0))
291
+ span.set_attribute(SemanticConvetion.GEN_AI_REQUEST_PRESENCE_PENALTY,
292
+ kwargs.get("presence_penalty", 0.0))
293
+ span.set_attribute(SemanticConvetion.GEN_AI_REQUEST_FREQUENCY_PENALTY,
294
+ kwargs.get("frequency_penalty", 0.0))
295
+ span.set_attribute(SemanticConvetion.GEN_AI_REQUEST_SEED,
296
+ kwargs.get("seed", ""))
297
+ span.set_attribute(SemanticConvetion.GEN_AI_REQUEST_IS_STREAM,
298
+ False)
299
+ if trace_content:
300
+ span.add_event(
301
+ name=SemanticConvetion.GEN_AI_CONTENT_PROMPT_EVENT,
302
+ attributes={
303
+ SemanticConvetion.GEN_AI_CONTENT_PROMPT: prompt,
304
+ },
305
+ )
306
+
307
+ # Set span attributes when tools is not passed to the function call
308
+ if "tools" not in kwargs:
309
+ # Calculate cost of the operation
310
+ cost = get_chat_model_cost(kwargs.get("model", "gpt-3.5-turbo"),
311
+ pricing_info, response_dict.get('usage', {}).get('prompt_tokens', None),
312
+ response_dict.get('usage', {}).get('completion_tokens', None))
313
+
314
+ span.set_attribute(SemanticConvetion.GEN_AI_USAGE_PROMPT_TOKENS,
315
+ response_dict.get('usage', {}).get('prompt_tokens', None))
316
+ span.set_attribute(SemanticConvetion.GEN_AI_USAGE_COMPLETION_TOKENS,
317
+ response_dict.get('usage', {}).get('completion_tokens', None))
318
+ span.set_attribute(SemanticConvetion.GEN_AI_USAGE_TOTAL_TOKENS,
319
+ response_dict.get('usage', {}).get('total_tokens', None))
320
+ span.set_attribute(SemanticConvetion.GEN_AI_RESPONSE_FINISH_REASON,
321
+ [response_dict.get('choices', [])[0].get('finish_reason', None)])
322
+ span.set_attribute(SemanticConvetion.GEN_AI_USAGE_COST,
323
+ cost)
324
+
325
+ # Set span attributes for when n = 1 (default)
326
+ if "n" not in kwargs or kwargs["n"] == 1:
327
+ if trace_content:
328
+ span.add_event(
329
+ name=SemanticConvetion.GEN_AI_CONTENT_COMPLETION_EVENT,
330
+ attributes={
331
+ SemanticConvetion.GEN_AI_CONTENT_COMPLETION: response_dict.get('choices', [])[0].get("message").get("content"),
332
+ },
333
+ )
334
+
335
+ # Set span attributes for when n > 0
336
+ else:
337
+ i = 0
338
+ while i < kwargs["n"] and trace_content is True:
339
+ attribute_name = f"gen_ai.content.completion.{i}"
340
+ span.add_event(
341
+ name=attribute_name,
342
+ attributes={
343
+ SemanticConvetion.GEN_AI_CONTENT_COMPLETION: response_dict.get('choices')[i].get("message").get("content"),
344
+ },
345
+ )
346
+ i += 1
347
+
348
+ # Return original response
349
+ return response
350
+
351
+ # Set span attributes when tools is passed to the function call
352
+ elif "tools" in kwargs:
353
+ # Calculate cost of the operation
354
+ cost = get_chat_model_cost(kwargs.get("model", "gpt-3.5-turbo"),
355
+ pricing_info, response_dict.get('usage').get('prompt_tokens'),
356
+ response_dict.get('usage').get('completion_tokens'))
357
+ span.add_event(
358
+ name=SemanticConvetion.GEN_AI_CONTENT_COMPLETION_EVENT,
359
+ attributes={
360
+ SemanticConvetion.GEN_AI_CONTENT_COMPLETION: "Function called with tools",
361
+ },
362
+ )
363
+ span.set_attribute(SemanticConvetion.GEN_AI_USAGE_PROMPT_TOKENS,
364
+ response_dict.get('usage').get('prompt_tokens'))
365
+ span.set_attribute(SemanticConvetion.GEN_AI_USAGE_COMPLETION_TOKENS,
366
+ response_dict.get('usage').get('completion_tokens'))
367
+ span.set_attribute(SemanticConvetion.GEN_AI_USAGE_TOTAL_TOKENS,
368
+ response_dict.get('usage').get('total_tokens'))
369
+ span.set_attribute(SemanticConvetion.GEN_AI_USAGE_COST,
370
+ cost)
371
+
372
+ span.set_status(Status(StatusCode.OK))
373
+
374
+ if disable_metrics is False:
375
+ attributes = {
376
+ TELEMETRY_SDK_NAME:
377
+ "openlit",
378
+ SemanticConvetion.GEN_AI_APPLICATION_NAME:
379
+ application_name,
380
+ SemanticConvetion.GEN_AI_SYSTEM:
381
+ SemanticConvetion.GEN_AI_SYSTEM_LITELLM,
382
+ SemanticConvetion.GEN_AI_ENVIRONMENT:
383
+ environment,
384
+ SemanticConvetion.GEN_AI_TYPE:
385
+ SemanticConvetion.GEN_AI_TYPE_CHAT,
386
+ SemanticConvetion.GEN_AI_REQUEST_MODEL:
387
+ kwargs.get("model", "gpt-3.5-turbo")
388
+ }
389
+
390
+ metrics["genai_requests"].add(1, attributes)
391
+ metrics["genai_total_tokens"].add(response_dict.get('usage').get('total_tokens'), attributes)
392
+ metrics["genai_completion_tokens"].add(response_dict.get('usage').get('completion_tokens'), attributes)
393
+ metrics["genai_prompt_tokens"].add(response_dict.get('usage').get('prompt_tokens'), attributes)
394
+ metrics["genai_cost"].record(cost, attributes)
395
+
396
+ # Return original response
397
+ return response
398
+
399
+ except Exception as e:
400
+ handle_exception(span, e)
401
+ logger.error("Error in trace creation: %s", e)
402
+
403
+ # Return original response
404
+ return response
405
+
406
+ return wrapper
@@ -0,0 +1,406 @@
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 LiteLLM SDK.
30
+ tracer: OpenTelemetry tracer for creating spans.
31
+ pricing_info: Information used for calculating the cost of LiteLLM 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
+
42
+ This class implements the '__aiter__' and '__anext__' methods that
43
+ handle asynchronous streaming responses.
44
+
45
+ This class also implements '__aenter__' and '__aexit__' methods that
46
+ handle asynchronous context management protocol.
47
+ """
48
+ def __init__(
49
+ self,
50
+ wrapped,
51
+ span,
52
+ kwargs,
53
+ **args,
54
+ ):
55
+ self.__wrapped__ = wrapped
56
+ self._span = span
57
+ # Placeholder for aggregating streaming response
58
+ self._llmresponse = ""
59
+ self._response_id = ""
60
+
61
+ self._args = args
62
+ self._kwargs = kwargs
63
+
64
+ def __enter__(self):
65
+ self.__wrapped__.__enter__()
66
+ return self
67
+
68
+ def __exit__(self, exc_type, exc_value, traceback):
69
+ self.__wrapped__.__exit__(exc_type, exc_value, traceback)
70
+
71
+ def __iter__(self):
72
+ return self
73
+
74
+ def __getattr__(self, name):
75
+ """Delegate attribute access to the wrapped object."""
76
+ return getattr(self.__wrapped__, name)
77
+
78
+ def __next__(self):
79
+ try:
80
+ chunk = self.__wrapped__.__next__()
81
+ chunked = response_as_dict(chunk)
82
+ # Collect message IDs and aggregated response from events
83
+ if (len(chunked.get('choices')) > 0 and ('delta' in chunked.get('choices')[0] and
84
+ 'content' in chunked.get('choices')[0].get('delta'))):
85
+
86
+ content = chunked.get('choices')[0].get('delta').get('content')
87
+ if content:
88
+ self._llmresponse += content
89
+ self._response_id = chunked.get('id')
90
+ return chunk
91
+ except StopIteration:
92
+ # Handling exception ensure observability without disrupting operation
93
+ try:
94
+ # Format 'messages' into a single string
95
+ message_prompt = self._kwargs.get("messages", "")
96
+ formatted_messages = []
97
+ for message in message_prompt:
98
+ role = message["role"]
99
+ content = message["content"]
100
+
101
+ if isinstance(content, list):
102
+ content_str = ", ".join(
103
+ # pylint: disable=line-too-long
104
+ f'{item["type"]}: {item["text"] if "text" in item else item["image_url"]}'
105
+ if "type" in item else f'text: {item["text"]}'
106
+ for item in content
107
+ )
108
+ formatted_messages.append(f"{role}: {content_str}")
109
+ else:
110
+ formatted_messages.append(f"{role}: {content}")
111
+ prompt = "\n".join(formatted_messages)
112
+
113
+ # Calculate tokens using input prompt and aggregated response
114
+ prompt_tokens = openai_tokens(prompt,
115
+ self._kwargs.get("model", "gpt-3.5-turbo"))
116
+ completion_tokens = openai_tokens(self._llmresponse,
117
+ self._kwargs.get("model", "gpt-3.5-turbo"))
118
+
119
+ # Calculate cost of the operation
120
+ cost = get_chat_model_cost(self._kwargs.get("model", "gpt-3.5-turbo"),
121
+ pricing_info, prompt_tokens,
122
+ completion_tokens)
123
+
124
+ # Set Span attributes
125
+ self._span.set_attribute(TELEMETRY_SDK_NAME, "openlit")
126
+ self._span.set_attribute(SemanticConvetion.GEN_AI_SYSTEM,
127
+ SemanticConvetion.GEN_AI_SYSTEM_LITELLM)
128
+ self._span.set_attribute(SemanticConvetion.GEN_AI_TYPE,
129
+ SemanticConvetion.GEN_AI_TYPE_CHAT)
130
+ self._span.set_attribute(SemanticConvetion.GEN_AI_ENDPOINT,
131
+ gen_ai_endpoint)
132
+ self._span.set_attribute(SemanticConvetion.GEN_AI_RESPONSE_ID,
133
+ self._response_id)
134
+ self._span.set_attribute(SemanticConvetion.GEN_AI_ENVIRONMENT,
135
+ environment)
136
+ self._span.set_attribute(SemanticConvetion.GEN_AI_APPLICATION_NAME,
137
+ application_name)
138
+ self._span.set_attribute(SemanticConvetion.GEN_AI_REQUEST_MODEL,
139
+ self._kwargs.get("model", "gpt-3.5-turbo"))
140
+ self._span.set_attribute(SemanticConvetion.GEN_AI_REQUEST_USER,
141
+ self._kwargs.get("user", ""))
142
+ self._span.set_attribute(SemanticConvetion.GEN_AI_REQUEST_TOP_P,
143
+ self._kwargs.get("top_p", 1.0))
144
+ self._span.set_attribute(SemanticConvetion.GEN_AI_REQUEST_MAX_TOKENS,
145
+ self._kwargs.get("max_tokens", -1))
146
+ self._span.set_attribute(SemanticConvetion.GEN_AI_REQUEST_TEMPERATURE,
147
+ self._kwargs.get("temperature", 1.0))
148
+ self._span.set_attribute(SemanticConvetion.GEN_AI_REQUEST_PRESENCE_PENALTY,
149
+ self._kwargs.get("presence_penalty", 0.0))
150
+ self._span.set_attribute(SemanticConvetion.GEN_AI_REQUEST_FREQUENCY_PENALTY,
151
+ self._kwargs.get("frequency_penalty", 0.0))
152
+ self._span.set_attribute(SemanticConvetion.GEN_AI_REQUEST_SEED,
153
+ self._kwargs.get("seed", ""))
154
+ self._span.set_attribute(SemanticConvetion.GEN_AI_REQUEST_IS_STREAM,
155
+ True)
156
+ self._span.set_attribute(SemanticConvetion.GEN_AI_USAGE_PROMPT_TOKENS,
157
+ prompt_tokens)
158
+ self._span.set_attribute(SemanticConvetion.GEN_AI_USAGE_COMPLETION_TOKENS,
159
+ completion_tokens)
160
+ self._span.set_attribute(SemanticConvetion.GEN_AI_USAGE_TOTAL_TOKENS,
161
+ prompt_tokens + completion_tokens)
162
+ self._span.set_attribute(SemanticConvetion.GEN_AI_USAGE_COST,
163
+ cost)
164
+ if trace_content:
165
+ self._span.add_event(
166
+ name=SemanticConvetion.GEN_AI_CONTENT_PROMPT_EVENT,
167
+ attributes={
168
+ SemanticConvetion.GEN_AI_CONTENT_PROMPT: prompt,
169
+ },
170
+ )
171
+ self._span.add_event(
172
+ name=SemanticConvetion.GEN_AI_CONTENT_COMPLETION_EVENT,
173
+ attributes={
174
+ SemanticConvetion.GEN_AI_CONTENT_COMPLETION: self._llmresponse,
175
+ },
176
+ )
177
+
178
+ self._span.set_status(Status(StatusCode.OK))
179
+
180
+ if disable_metrics is False:
181
+ attributes = {
182
+ TELEMETRY_SDK_NAME:
183
+ "openlit",
184
+ SemanticConvetion.GEN_AI_APPLICATION_NAME:
185
+ application_name,
186
+ SemanticConvetion.GEN_AI_SYSTEM:
187
+ SemanticConvetion.GEN_AI_SYSTEM_LITELLM,
188
+ SemanticConvetion.GEN_AI_ENVIRONMENT:
189
+ environment,
190
+ SemanticConvetion.GEN_AI_TYPE:
191
+ SemanticConvetion.GEN_AI_TYPE_CHAT,
192
+ SemanticConvetion.GEN_AI_REQUEST_MODEL:
193
+ self._kwargs.get("model", "gpt-3.5-turbo")
194
+ }
195
+
196
+ metrics["genai_requests"].add(1, attributes)
197
+ metrics["genai_total_tokens"].add(
198
+ prompt_tokens + completion_tokens, attributes
199
+ )
200
+ metrics["genai_completion_tokens"].add(completion_tokens, attributes)
201
+ metrics["genai_prompt_tokens"].add(prompt_tokens, attributes)
202
+ metrics["genai_cost"].record(cost, attributes)
203
+
204
+ except Exception as e:
205
+ handle_exception(self._span, e)
206
+ logger.error("Error in trace creation: %s", e)
207
+ finally:
208
+ self._span.end()
209
+ raise
210
+
211
+ def wrapper(wrapped, instance, args, kwargs):
212
+ """
213
+ Wraps the 'chat.completions' API call to add telemetry.
214
+
215
+ This collects metrics such as execution time, cost, and token usage, and handles errors
216
+ gracefully, adding details to the trace for observability.
217
+
218
+ Args:
219
+ wrapped: The original 'chat.completions' method to be wrapped.
220
+ instance: The instance of the class where the original method is defined.
221
+ args: Positional arguments for the 'chat.completions' method.
222
+ kwargs: Keyword arguments for the 'chat.completions' method.
223
+
224
+ Returns:
225
+ The response from the original 'chat.completions' method.
226
+ """
227
+
228
+ # Check if streaming is enabled for the API call
229
+ streaming = kwargs.get("stream", False)
230
+
231
+ # pylint: disable=no-else-return
232
+ if streaming:
233
+ # Special handling for streaming response to accommodate the nature of data flow
234
+ awaited_wrapped = wrapped(*args, **kwargs)
235
+ span = tracer.start_span(gen_ai_endpoint, kind=SpanKind.CLIENT)
236
+
237
+ return TracedSyncStream(awaited_wrapped, span, kwargs)
238
+
239
+ # Handling for non-streaming responses
240
+ else:
241
+ # pylint: disable=line-too-long
242
+ with tracer.start_as_current_span(gen_ai_endpoint, kind= SpanKind.CLIENT) as span:
243
+ response = wrapped(*args, **kwargs)
244
+
245
+ response_dict = response_as_dict(response)
246
+
247
+ try:
248
+ # Format 'messages' into a single string
249
+ message_prompt = kwargs.get("messages", "")
250
+ formatted_messages = []
251
+ for message in message_prompt:
252
+ role = message["role"]
253
+ content = message["content"]
254
+
255
+ if isinstance(content, list):
256
+ content_str = ", ".join(
257
+ # pylint: disable=line-too-long
258
+ f'{item["type"]}: {item["text"] if "text" in item else item["image_url"]}'
259
+ if "type" in item else f'text: {item["text"]}'
260
+ for item in content
261
+ )
262
+ formatted_messages.append(f"{role}: {content_str}")
263
+ else:
264
+ formatted_messages.append(f"{role}: {content}")
265
+ prompt = "\n".join(formatted_messages)
266
+
267
+ # Set base span attribues
268
+ span.set_attribute(TELEMETRY_SDK_NAME, "openlit")
269
+ span.set_attribute(SemanticConvetion.GEN_AI_SYSTEM,
270
+ SemanticConvetion.GEN_AI_SYSTEM_LITELLM)
271
+ span.set_attribute(SemanticConvetion.GEN_AI_TYPE,
272
+ SemanticConvetion.GEN_AI_TYPE_CHAT)
273
+ span.set_attribute(SemanticConvetion.GEN_AI_ENDPOINT,
274
+ gen_ai_endpoint)
275
+ span.set_attribute(SemanticConvetion.GEN_AI_RESPONSE_ID,
276
+ response_dict.get("id"))
277
+ span.set_attribute(SemanticConvetion.GEN_AI_ENVIRONMENT,
278
+ environment)
279
+ span.set_attribute(SemanticConvetion.GEN_AI_APPLICATION_NAME,
280
+ application_name)
281
+ span.set_attribute(SemanticConvetion.GEN_AI_REQUEST_MODEL,
282
+ kwargs.get("model", "gpt-3.5-turbo"))
283
+ span.set_attribute(SemanticConvetion.GEN_AI_REQUEST_TOP_P,
284
+ kwargs.get("top_p", 1.0))
285
+ span.set_attribute(SemanticConvetion.GEN_AI_REQUEST_MAX_TOKENS,
286
+ kwargs.get("max_tokens", -1))
287
+ span.set_attribute(SemanticConvetion.GEN_AI_REQUEST_USER,
288
+ kwargs.get("user", ""))
289
+ span.set_attribute(SemanticConvetion.GEN_AI_REQUEST_TEMPERATURE,
290
+ kwargs.get("temperature", 1.0))
291
+ span.set_attribute(SemanticConvetion.GEN_AI_REQUEST_PRESENCE_PENALTY,
292
+ kwargs.get("presence_penalty", 0.0))
293
+ span.set_attribute(SemanticConvetion.GEN_AI_REQUEST_FREQUENCY_PENALTY,
294
+ kwargs.get("frequency_penalty", 0.0))
295
+ span.set_attribute(SemanticConvetion.GEN_AI_REQUEST_SEED,
296
+ kwargs.get("seed", ""))
297
+ span.set_attribute(SemanticConvetion.GEN_AI_REQUEST_IS_STREAM,
298
+ False)
299
+ if trace_content:
300
+ span.add_event(
301
+ name=SemanticConvetion.GEN_AI_CONTENT_PROMPT_EVENT,
302
+ attributes={
303
+ SemanticConvetion.GEN_AI_CONTENT_PROMPT: prompt,
304
+ },
305
+ )
306
+
307
+ # Set span attributes when tools is not passed to the function call
308
+ if "tools" not in kwargs:
309
+ # Calculate cost of the operation
310
+ cost = get_chat_model_cost(kwargs.get("model", "gpt-3.5-turbo"),
311
+ pricing_info, response_dict.get('usage', {}).get('prompt_tokens', None),
312
+ response_dict.get('usage', {}).get('completion_tokens', None))
313
+
314
+ span.set_attribute(SemanticConvetion.GEN_AI_USAGE_PROMPT_TOKENS,
315
+ response_dict.get('usage', {}).get('prompt_tokens', None))
316
+ span.set_attribute(SemanticConvetion.GEN_AI_USAGE_COMPLETION_TOKENS,
317
+ response_dict.get('usage', {}).get('completion_tokens', None))
318
+ span.set_attribute(SemanticConvetion.GEN_AI_USAGE_TOTAL_TOKENS,
319
+ response_dict.get('usage', {}).get('total_tokens', None))
320
+ span.set_attribute(SemanticConvetion.GEN_AI_RESPONSE_FINISH_REASON,
321
+ [response_dict.get('choices', [])[0].get('finish_reason', None)])
322
+ span.set_attribute(SemanticConvetion.GEN_AI_USAGE_COST,
323
+ cost)
324
+
325
+ # Set span attributes for when n = 1 (default)
326
+ if "n" not in kwargs or kwargs["n"] == 1:
327
+ if trace_content:
328
+ span.add_event(
329
+ name=SemanticConvetion.GEN_AI_CONTENT_COMPLETION_EVENT,
330
+ attributes={
331
+ SemanticConvetion.GEN_AI_CONTENT_COMPLETION: response_dict.get('choices', [])[0].get("message").get("content"),
332
+ },
333
+ )
334
+
335
+ # Set span attributes for when n > 0
336
+ else:
337
+ i = 0
338
+ while i < kwargs["n"] and trace_content is True:
339
+ attribute_name = f"gen_ai.content.completion.{i}"
340
+ span.add_event(
341
+ name=attribute_name,
342
+ attributes={
343
+ SemanticConvetion.GEN_AI_CONTENT_COMPLETION: response_dict.get('choices')[i].get("message").get("content"),
344
+ },
345
+ )
346
+ i += 1
347
+
348
+ # Return original response
349
+ return response
350
+
351
+ # Set span attributes when tools is passed to the function call
352
+ elif "tools" in kwargs:
353
+ # Calculate cost of the operation
354
+ cost = get_chat_model_cost(kwargs.get("model", "gpt-3.5-turbo"),
355
+ pricing_info, response_dict.get('usage').get('prompt_tokens'),
356
+ response_dict.get('usage').get('completion_tokens'))
357
+ span.add_event(
358
+ name=SemanticConvetion.GEN_AI_CONTENT_COMPLETION_EVENT,
359
+ attributes={
360
+ SemanticConvetion.GEN_AI_CONTENT_COMPLETION: "Function called with tools",
361
+ },
362
+ )
363
+ span.set_attribute(SemanticConvetion.GEN_AI_USAGE_PROMPT_TOKENS,
364
+ response_dict.get('usage').get('prompt_tokens'))
365
+ span.set_attribute(SemanticConvetion.GEN_AI_USAGE_COMPLETION_TOKENS,
366
+ response_dict.get('usage').get('completion_tokens'))
367
+ span.set_attribute(SemanticConvetion.GEN_AI_USAGE_TOTAL_TOKENS,
368
+ response_dict.get('usage').get('total_tokens'))
369
+ span.set_attribute(SemanticConvetion.GEN_AI_USAGE_COST,
370
+ cost)
371
+
372
+ span.set_status(Status(StatusCode.OK))
373
+
374
+ if disable_metrics is False:
375
+ attributes = {
376
+ TELEMETRY_SDK_NAME:
377
+ "openlit",
378
+ SemanticConvetion.GEN_AI_APPLICATION_NAME:
379
+ application_name,
380
+ SemanticConvetion.GEN_AI_SYSTEM:
381
+ SemanticConvetion.GEN_AI_SYSTEM_LITELLM,
382
+ SemanticConvetion.GEN_AI_ENVIRONMENT:
383
+ environment,
384
+ SemanticConvetion.GEN_AI_TYPE:
385
+ SemanticConvetion.GEN_AI_TYPE_CHAT,
386
+ SemanticConvetion.GEN_AI_REQUEST_MODEL:
387
+ kwargs.get("model", "gpt-3.5-turbo")
388
+ }
389
+
390
+ metrics["genai_requests"].add(1, attributes)
391
+ metrics["genai_total_tokens"].add(response_dict.get('usage').get('total_tokens'), attributes)
392
+ metrics["genai_completion_tokens"].add(response_dict.get('usage').get('completion_tokens'), attributes)
393
+ metrics["genai_prompt_tokens"].add(response_dict.get('usage').get('prompt_tokens'), attributes)
394
+ metrics["genai_cost"].record(cost, attributes)
395
+
396
+ # Return original response
397
+ return response
398
+
399
+ except Exception as e:
400
+ handle_exception(span, e)
401
+ logger.error("Error in trace creation: %s", e)
402
+
403
+ # Return original response
404
+ return response
405
+
406
+ 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,
@@ -88,6 +88,7 @@ class SemanticConvetion:
88
88
  GEN_AI_TYPE_FINETUNING = "fine_tuning"
89
89
  GEN_AI_TYPE_VECTORDB = "vectordb"
90
90
  GEN_AI_TYPE_FRAMEWORK = "framework"
91
+ GEN_AI_TYPE_AGENT = "agent"
91
92
 
92
93
  GEN_AI_SYSTEM_HUGGING_FACE = "huggingface"
93
94
  GEN_AI_SYSTEM_OPENAI = "openai"
@@ -108,6 +109,8 @@ class SemanticConvetion:
108
109
  GEN_AI_SYSTEM_LLAMAINDEX = "llama_index"
109
110
  GEN_AI_SYSTEM_HAYSTACK = "haystack"
110
111
  GEN_AI_SYSTEM_EMBEDCHAIN = "embedchain"
112
+ GEN_AI_SYSTEM_LITELLM = "litellm"
113
+ GEN_AI_SYSTEM_CREWAI = "crewai"
111
114
 
112
115
  # Vector DB
113
116
  DB_REQUESTS = "db.total.requests"
@@ -154,6 +157,24 @@ class SemanticConvetion:
154
157
  DB_SYSTEM_QDRANT = "qdrant"
155
158
  DB_SYSTEM_MILVUS = "milvus"
156
159
 
160
+ # Agents
161
+ GEN_AI_AGENT_ID = "gen_ai.agent.id"
162
+ GEN_AI_AGENT_TASK_ID = "gen_ai.agent.task.id"
163
+ GEN_AI_AGENT_ROLE = "gen_ai.agent.role"
164
+ GEN_AI_AGENT_GOAL = "gen_ai.agent.goal"
165
+ GEN_AI_AGENT_CONTEXT = "gen_ai.agent.context"
166
+ GEN_AI_AGENT_ENABLE_CACHE = "gen_ai.agent.enable_cache"
167
+ GEN_AI_AGENT_ALLOW_DELEGATION = "gen_ai.agent.allow_delegation"
168
+ GEN_AI_AGENT_ALLOW_CODE_EXECUTION = "gen_ai.agent.allow_code_execution"
169
+ GEN_AI_AGENT_MAX_RETRY_LIMIT = "gen_ai.agent.max_retry_limit"
170
+ GEN_AI_AGENT_TOOLS = "gen_ai.agent.tools"
171
+ GEN_AI_AGENT_TOOL_RESULTS = "gen_ai.agent.tool_results"
172
+ GEN_AI_AGENT_TASK = "gen_ai.agent.task"
173
+ GEN_AI_AGENT_EXPECTED_OUTPUT = "gen_ai.agent.expected_output"
174
+ GEN_AI_AGENT_ACTUAL_OUTPUT = "gen_ai.agent.actual_output"
175
+ GEN_AI_AGENT_HUMAN_INPUT = "gen_ai.agent.human_input"
176
+ GEN_AI_AGENT_TASK_ASSOCIATION = "gen_ai.agent.task_associations"
177
+
157
178
  # GPU
158
179
  GPU_INDEX = "gpu.index"
159
180
  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.1
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=V0ZAlNf6vPL6nZs_XvQYG2DqpgfbX_37yMnScAu3dsk,6917
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=fmOpzjhfnYubFdlJYA7R0n2rxxrO78FBb6q1iCf2_HQ,21829
49
+ openlit/instrumentation/litellm/litellm.py,sha256=zO-L8-Yai0uqDl4J7i7Y8ETL87EpozevfgQdGMLsu4Y,21742
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=_IjU498Sc0Rjz55y9S3dUelgRalmrzzBgFglPzOlIfk,9137
80
+ openlit-1.30.1.dist-info/LICENSE,sha256=xx0jnfkXJvxRnG63LTGOxlggYnIysveWIZ6H3PNdCrQ,11357
81
+ openlit-1.30.1.dist-info/METADATA,sha256=Q83fnSGICFk7AgR8xiVKGFN8bHcq3V9vmCG8UrJW0Hk,20841
82
+ openlit-1.30.1.dist-info/WHEEL,sha256=Nq82e9rUAnEjt98J6MlVmMCZb-t9cYE2Ir1kpBmnWfs,88
83
+ openlit-1.30.1.dist-info/RECORD,,