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.
- openlit/__helpers.py +14 -0
- openlit/__init__.py +11 -3
- openlit/evals/utils.py +5 -2
- openlit/guard/utils.py +5 -1
- openlit/instrumentation/azure_ai_inference/async_azure_ai_inference.py +0 -1
- openlit/instrumentation/azure_ai_inference/azure_ai_inference.py +0 -1
- openlit/instrumentation/crewai/__init__.py +50 -0
- openlit/instrumentation/crewai/crewai.py +149 -0
- openlit/instrumentation/google_ai_studio/google_ai_studio.py +0 -1
- openlit/instrumentation/litellm/__init__.py +54 -0
- openlit/instrumentation/litellm/async_litellm.py +406 -0
- openlit/instrumentation/litellm/litellm.py +406 -0
- openlit/instrumentation/openai/async_openai.py +63 -36
- openlit/instrumentation/openai/openai.py +208 -156
- openlit/otel/metrics.py +6 -3
- openlit/otel/tracing.py +5 -2
- openlit/semcov/__init__.py +21 -0
- {openlit-1.29.2.dist-info → openlit-1.30.2.dist-info}/METADATA +11 -11
- {openlit-1.29.2.dist-info → openlit-1.30.2.dist-info}/RECORD +21 -16
- {openlit-1.29.2.dist-info → openlit-1.30.2.dist-info}/LICENSE +0 -0
- {openlit-1.29.2.dist-info → openlit-1.30.2.dist-info}/WHEEL +0 -0
@@ -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
|
@@ -6,8 +6,15 @@ Module for monitoring OpenAI API calls.
|
|
6
6
|
import logging
|
7
7
|
from opentelemetry.trace import SpanKind, Status, StatusCode
|
8
8
|
from opentelemetry.sdk.resources import TELEMETRY_SDK_NAME
|
9
|
-
from openlit.__helpers import
|
10
|
-
|
9
|
+
from openlit.__helpers import (
|
10
|
+
get_chat_model_cost,
|
11
|
+
get_embed_model_cost,
|
12
|
+
get_audio_model_cost,
|
13
|
+
get_image_model_cost,
|
14
|
+
openai_tokens,
|
15
|
+
handle_exception,
|
16
|
+
response_as_dict,
|
17
|
+
)
|
11
18
|
from openlit.semcov import SemanticConvetion
|
12
19
|
|
13
20
|
# Initialize logger for logging potential issues and operations
|
@@ -46,8 +53,8 @@ def async_chat_completions(gen_ai_endpoint, version, environment, application_na
|
|
46
53
|
self,
|
47
54
|
wrapped,
|
48
55
|
span,
|
49
|
-
|
50
|
-
**
|
56
|
+
kwargs,
|
57
|
+
**args,
|
51
58
|
):
|
52
59
|
self.__wrapped__ = wrapped
|
53
60
|
self._span = span
|
@@ -68,17 +75,22 @@ def async_chat_completions(gen_ai_endpoint, version, environment, application_na
|
|
68
75
|
def __aiter__(self):
|
69
76
|
return self
|
70
77
|
|
78
|
+
async def __getattr__(self, name):
|
79
|
+
"""Delegate attribute access to the wrapped object."""
|
80
|
+
return getattr(await self.__wrapped__, name)
|
81
|
+
|
71
82
|
async def __anext__(self):
|
72
83
|
try:
|
73
84
|
chunk = await self.__wrapped__.__anext__()
|
85
|
+
chunked = response_as_dict(chunk)
|
74
86
|
# Collect message IDs and aggregated response from events
|
75
|
-
if len(
|
76
|
-
|
77
|
-
|
78
|
-
|
79
|
-
|
80
|
-
|
81
|
-
self._response_id =
|
87
|
+
if (len(chunked.get('choices')) > 0 and ('delta' in chunked.get('choices')[0] and
|
88
|
+
'content' in chunked.get('choices')[0].get('delta'))):
|
89
|
+
|
90
|
+
content = chunked.get('choices')[0].get('delta').get('content')
|
91
|
+
if content:
|
92
|
+
self._llmresponse += content
|
93
|
+
self._response_id = chunked.get('id')
|
82
94
|
return chunk
|
83
95
|
except StopAsyncIteration:
|
84
96
|
# Handling exception ensure observability without disrupting operation
|
@@ -226,7 +238,7 @@ def async_chat_completions(gen_ai_endpoint, version, environment, application_na
|
|
226
238
|
awaited_wrapped = await wrapped(*args, **kwargs)
|
227
239
|
span = tracer.start_span(gen_ai_endpoint, kind=SpanKind.CLIENT)
|
228
240
|
|
229
|
-
return TracedAsyncStream(awaited_wrapped, span)
|
241
|
+
return TracedAsyncStream(awaited_wrapped, span, kwargs)
|
230
242
|
|
231
243
|
# Handling for non-streaming responses
|
232
244
|
else:
|
@@ -234,6 +246,8 @@ def async_chat_completions(gen_ai_endpoint, version, environment, application_na
|
|
234
246
|
with tracer.start_as_current_span(gen_ai_endpoint, kind= SpanKind.CLIENT) as span:
|
235
247
|
response = await wrapped(*args, **kwargs)
|
236
248
|
|
249
|
+
response_dict = response_as_dict(response)
|
250
|
+
|
237
251
|
try:
|
238
252
|
# Format 'messages' into a single string
|
239
253
|
message_prompt = kwargs.get("messages", "")
|
@@ -263,7 +277,7 @@ def async_chat_completions(gen_ai_endpoint, version, environment, application_na
|
|
263
277
|
span.set_attribute(SemanticConvetion.GEN_AI_ENDPOINT,
|
264
278
|
gen_ai_endpoint)
|
265
279
|
span.set_attribute(SemanticConvetion.GEN_AI_RESPONSE_ID,
|
266
|
-
|
280
|
+
response_dict.get("id"))
|
267
281
|
span.set_attribute(SemanticConvetion.GEN_AI_ENVIRONMENT,
|
268
282
|
environment)
|
269
283
|
span.set_attribute(SemanticConvetion.GEN_AI_APPLICATION_NAME,
|
@@ -294,23 +308,21 @@ def async_chat_completions(gen_ai_endpoint, version, environment, application_na
|
|
294
308
|
},
|
295
309
|
)
|
296
310
|
|
297
|
-
span.set_status(Status(StatusCode.OK))
|
298
|
-
|
299
311
|
# Set span attributes when tools is not passed to the function call
|
300
312
|
if "tools" not in kwargs:
|
301
313
|
# Calculate cost of the operation
|
302
314
|
cost = get_chat_model_cost(kwargs.get("model", "gpt-3.5-turbo"),
|
303
|
-
pricing_info,
|
304
|
-
|
315
|
+
pricing_info, response_dict.get('usage', {}).get('prompt_tokens', None),
|
316
|
+
response_dict.get('usage', {}).get('completion_tokens', None))
|
305
317
|
|
306
318
|
span.set_attribute(SemanticConvetion.GEN_AI_USAGE_PROMPT_TOKENS,
|
307
|
-
|
319
|
+
response_dict.get('usage', {}).get('prompt_tokens', None))
|
308
320
|
span.set_attribute(SemanticConvetion.GEN_AI_USAGE_COMPLETION_TOKENS,
|
309
|
-
|
321
|
+
response_dict.get('usage', {}).get('completion_tokens', None))
|
310
322
|
span.set_attribute(SemanticConvetion.GEN_AI_USAGE_TOTAL_TOKENS,
|
311
|
-
|
323
|
+
response_dict.get('usage', {}).get('total_tokens', None))
|
312
324
|
span.set_attribute(SemanticConvetion.GEN_AI_RESPONSE_FINISH_REASON,
|
313
|
-
|
325
|
+
[response_dict.get('choices', [])[0].get('finish_reason', None)])
|
314
326
|
span.set_attribute(SemanticConvetion.GEN_AI_USAGE_COST,
|
315
327
|
cost)
|
316
328
|
|
@@ -320,7 +332,7 @@ def async_chat_completions(gen_ai_endpoint, version, environment, application_na
|
|
320
332
|
span.add_event(
|
321
333
|
name=SemanticConvetion.GEN_AI_CONTENT_COMPLETION_EVENT,
|
322
334
|
attributes={
|
323
|
-
SemanticConvetion.GEN_AI_CONTENT_COMPLETION:
|
335
|
+
SemanticConvetion.GEN_AI_CONTENT_COMPLETION: response_dict.get('choices', [])[0].get("message").get("content"),
|
324
336
|
},
|
325
337
|
)
|
326
338
|
|
@@ -332,7 +344,7 @@ def async_chat_completions(gen_ai_endpoint, version, environment, application_na
|
|
332
344
|
span.add_event(
|
333
345
|
name=attribute_name,
|
334
346
|
attributes={
|
335
|
-
SemanticConvetion.GEN_AI_CONTENT_COMPLETION:
|
347
|
+
SemanticConvetion.GEN_AI_CONTENT_COMPLETION: response_dict.get('choices')[i].get("message").get("content"),
|
336
348
|
},
|
337
349
|
)
|
338
350
|
i += 1
|
@@ -344,9 +356,8 @@ def async_chat_completions(gen_ai_endpoint, version, environment, application_na
|
|
344
356
|
elif "tools" in kwargs:
|
345
357
|
# Calculate cost of the operation
|
346
358
|
cost = get_chat_model_cost(kwargs.get("model", "gpt-3.5-turbo"),
|
347
|
-
pricing_info,
|
348
|
-
|
349
|
-
|
359
|
+
pricing_info, response_dict.get('usage').get('prompt_tokens'),
|
360
|
+
response_dict.get('usage').get('completion_tokens'))
|
350
361
|
span.add_event(
|
351
362
|
name=SemanticConvetion.GEN_AI_CONTENT_COMPLETION_EVENT,
|
352
363
|
attributes={
|
@@ -354,11 +365,11 @@ def async_chat_completions(gen_ai_endpoint, version, environment, application_na
|
|
354
365
|
},
|
355
366
|
)
|
356
367
|
span.set_attribute(SemanticConvetion.GEN_AI_USAGE_PROMPT_TOKENS,
|
357
|
-
|
368
|
+
response_dict.get('usage').get('prompt_tokens'))
|
358
369
|
span.set_attribute(SemanticConvetion.GEN_AI_USAGE_COMPLETION_TOKENS,
|
359
|
-
|
370
|
+
response_dict.get('usage').get('completion_tokens'))
|
360
371
|
span.set_attribute(SemanticConvetion.GEN_AI_USAGE_TOTAL_TOKENS,
|
361
|
-
|
372
|
+
response_dict.get('usage').get('total_tokens'))
|
362
373
|
span.set_attribute(SemanticConvetion.GEN_AI_USAGE_COST,
|
363
374
|
cost)
|
364
375
|
|
@@ -381,9 +392,9 @@ def async_chat_completions(gen_ai_endpoint, version, environment, application_na
|
|
381
392
|
}
|
382
393
|
|
383
394
|
metrics["genai_requests"].add(1, attributes)
|
384
|
-
metrics["genai_total_tokens"].add(
|
385
|
-
metrics["genai_completion_tokens"].add(
|
386
|
-
metrics["genai_prompt_tokens"].add(
|
395
|
+
metrics["genai_total_tokens"].add(response_dict.get('usage').get('total_tokens'), attributes)
|
396
|
+
metrics["genai_completion_tokens"].add(response_dict.get('usage').get('completion_tokens'), attributes)
|
397
|
+
metrics["genai_prompt_tokens"].add(response_dict.get('usage').get('prompt_tokens'), attributes)
|
387
398
|
metrics["genai_cost"].record(cost, attributes)
|
388
399
|
|
389
400
|
# Return original response
|
@@ -457,8 +468,8 @@ def async_embedding(gen_ai_endpoint, version, environment, application_name,
|
|
457
468
|
kwargs.get("model", "text-embedding-ada-002"))
|
458
469
|
span.set_attribute(SemanticConvetion.GEN_AI_REQUEST_EMBEDDING_FORMAT,
|
459
470
|
kwargs.get("encoding_format", "float"))
|
460
|
-
span.set_attribute(SemanticConvetion.GEN_AI_REQUEST_EMBEDDING_DIMENSION,
|
461
|
-
|
471
|
+
# span.set_attribute(SemanticConvetion.GEN_AI_REQUEST_EMBEDDING_DIMENSION,
|
472
|
+
# kwargs.get("dimensions", "null"))
|
462
473
|
span.set_attribute(SemanticConvetion.GEN_AI_REQUEST_USER,
|
463
474
|
kwargs.get("user", ""))
|
464
475
|
span.set_attribute(SemanticConvetion.GEN_AI_USAGE_PROMPT_TOKENS,
|
@@ -548,13 +559,14 @@ def async_finetune(gen_ai_endpoint, version, environment, application_name,
|
|
548
559
|
with tracer.start_as_current_span(gen_ai_endpoint, kind= SpanKind.CLIENT) as span:
|
549
560
|
response = await wrapped(*args, **kwargs)
|
550
561
|
|
562
|
+
# Handling exception ensure observability without disrupting operation
|
551
563
|
try:
|
552
564
|
# Set Span attributes
|
553
565
|
span.set_attribute(TELEMETRY_SDK_NAME, "openlit")
|
554
566
|
span.set_attribute(SemanticConvetion.GEN_AI_SYSTEM,
|
555
567
|
SemanticConvetion.GEN_AI_SYSTEM_OPENAI)
|
556
568
|
span.set_attribute(SemanticConvetion.GEN_AI_TYPE,
|
557
|
-
|
569
|
+
SemanticConvetion.GEN_AI_TYPE_FINETUNING)
|
558
570
|
span.set_attribute(SemanticConvetion.GEN_AI_ENDPOINT,
|
559
571
|
gen_ai_endpoint)
|
560
572
|
span.set_attribute(SemanticConvetion.GEN_AI_ENVIRONMENT,
|
@@ -585,7 +597,22 @@ def async_finetune(gen_ai_endpoint, version, environment, application_name,
|
|
585
597
|
span.set_status(Status(StatusCode.OK))
|
586
598
|
|
587
599
|
if disable_metrics is False:
|
588
|
-
|
600
|
+
attributes = {
|
601
|
+
TELEMETRY_SDK_NAME:
|
602
|
+
"openlit",
|
603
|
+
SemanticConvetion.GEN_AI_APPLICATION_NAME:
|
604
|
+
application_name,
|
605
|
+
SemanticConvetion.GEN_AI_SYSTEM:
|
606
|
+
SemanticConvetion.GEN_AI_SYSTEM_OPENAI,
|
607
|
+
SemanticConvetion.GEN_AI_ENVIRONMENT:
|
608
|
+
environment,
|
609
|
+
SemanticConvetion.GEN_AI_TYPE:
|
610
|
+
SemanticConvetion.GEN_AI_TYPE_FINETUNING,
|
611
|
+
SemanticConvetion.GEN_AI_REQUEST_MODEL:
|
612
|
+
kwargs.get("model", "gpt-3.5-turbo")
|
613
|
+
}
|
614
|
+
|
615
|
+
metrics["genai_requests"].add(1, attributes)
|
589
616
|
|
590
617
|
# Return original response
|
591
618
|
return response
|