openlit 1.29.2__py3-none-any.whl → 1.30.2__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,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