openlit 1.5.0__py3-none-any.whl → 1.6.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
openlit/__init__.py CHANGED
@@ -20,6 +20,7 @@ from openlit.instrumentation.mistral import MistralInstrumentor
20
20
  from openlit.instrumentation.bedrock import BedrockInstrumentor
21
21
  from openlit.instrumentation.vertexai import VertexAIInstrumentor
22
22
  from openlit.instrumentation.groq import GroqInstrumentor
23
+ from openlit.instrumentation.ollama import OllamaInstrumentor
23
24
  from openlit.instrumentation.langchain import LangChainInstrumentor
24
25
  from openlit.instrumentation.llamaindex import LlamaIndexInstrumentor
25
26
  from openlit.instrumentation.haystack import HaystackInstrumentor
@@ -154,6 +155,7 @@ def init(environment="default", application_name="default", tracer=None, otlp_en
154
155
  "bedrock": "boto3",
155
156
  "vertexai": "vertexai",
156
157
  "groq": "groq",
158
+ "ollama": "ollama",
157
159
  "langchain": "langchain",
158
160
  "llama_index": "llama_index",
159
161
  "haystack": "haystack",
@@ -206,6 +208,7 @@ def init(environment="default", application_name="default", tracer=None, otlp_en
206
208
  "bedrock": BedrockInstrumentor(),
207
209
  "vertexai": VertexAIInstrumentor(),
208
210
  "groq": GroqInstrumentor(),
211
+ "ollama": OllamaInstrumentor(),
209
212
  "langchain": LangChainInstrumentor(),
210
213
  "llama_index": LlamaIndexInstrumentor(),
211
214
  "haystack": HaystackInstrumentor(),
@@ -0,0 +1,104 @@
1
+ # pylint: disable=useless-return, bad-staticmethod-argument, disable=duplicate-code
2
+ """Initializer of Auto Instrumentation of Ollama 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.ollama.ollama import (
10
+ chat, embeddings, generate
11
+ )
12
+ from openlit.instrumentation.ollama.async_ollama import (
13
+ async_chat, async_embeddings, async_generate
14
+ )
15
+
16
+ _instruments = ("ollama >= 0.2.0",)
17
+
18
+ class OllamaInstrumentor(BaseInstrumentor):
19
+ """
20
+ An instrumentor for Ollama'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("ollama")
35
+
36
+ # sync chat
37
+ wrap_function_wrapper(
38
+ "ollama",
39
+ "chat",
40
+ chat("ollama.chat", version, environment, application_name,
41
+ tracer, pricing_info, trace_content, metrics, disable_metrics),
42
+ )
43
+ wrap_function_wrapper(
44
+ "ollama",
45
+ "Client.chat",
46
+ chat("ollama.chat", version, environment, application_name,
47
+ tracer, pricing_info, trace_content, metrics, disable_metrics),
48
+ )
49
+
50
+ # sync embeddings
51
+ wrap_function_wrapper(
52
+ "ollama",
53
+ "embeddings",
54
+ embeddings("ollama.embeddings", version, environment, application_name,
55
+ tracer, pricing_info, trace_content, metrics, disable_metrics),
56
+ )
57
+ wrap_function_wrapper(
58
+ "ollama",
59
+ "Client.embeddings",
60
+ embeddings("ollama.embeddings", version, environment, application_name,
61
+ tracer, pricing_info, trace_content, metrics, disable_metrics),
62
+ )
63
+
64
+ # sync generate
65
+ wrap_function_wrapper(
66
+ "ollama",
67
+ "generate",
68
+ generate("ollama.generate", version, environment, application_name,
69
+ tracer, pricing_info, trace_content, metrics, disable_metrics),
70
+ )
71
+ wrap_function_wrapper(
72
+ "ollama",
73
+ "Client.generate",
74
+ generate("ollama.generate", version, environment, application_name,
75
+ tracer, pricing_info, trace_content, metrics, disable_metrics),
76
+ )
77
+
78
+ # async chat
79
+ wrap_function_wrapper(
80
+ "ollama",
81
+ "AsyncClient.chat",
82
+ async_chat("ollama.chat", version, environment, application_name,
83
+ tracer, pricing_info, trace_content, metrics, disable_metrics),
84
+ )
85
+
86
+ # async embeddings
87
+ wrap_function_wrapper(
88
+ "ollama",
89
+ "AsyncClient.embeddings",
90
+ async_embeddings("ollama.embeddings", version, environment, application_name,
91
+ tracer, pricing_info, trace_content, metrics, disable_metrics),
92
+ )
93
+
94
+ # aync generate
95
+ wrap_function_wrapper(
96
+ "ollama",
97
+ "AsyncClient.generate",
98
+ async_generate("ollama.generate", version, environment, application_name,
99
+ tracer, pricing_info, trace_content, metrics, disable_metrics),
100
+ )
101
+
102
+ def _uninstrument(self, **kwargs):
103
+ # Proper uninstrumentation logic to revert patched methods
104
+ pass
@@ -0,0 +1,564 @@
1
+ # pylint: disable=duplicate-code, broad-exception-caught, too-many-statements, unused-argument, possibly-used-before-assignment
2
+ """
3
+ Module for monitoring Ollama API 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 handle_exception, general_tokens
10
+ from openlit.semcov import SemanticConvetion
11
+
12
+ # Initialize logger for logging potential issues and operations
13
+ logger = logging.getLogger(__name__)
14
+
15
+ def async_chat(gen_ai_endpoint, version, environment, application_name,
16
+ tracer, pricing_info, trace_content, metrics, disable_metrics):
17
+ """
18
+ Generates a telemetry wrapper for chat to collect metrics.
19
+
20
+ Args:
21
+ gen_ai_endpoint: Endpoint identifier for logging and tracing.
22
+ version: Version of the monitoring package.
23
+ environment: Deployment environment (e.g., production, staging).
24
+ application_name: Name of the application using the Ollama API.
25
+ tracer: OpenTelemetry tracer for creating spans.
26
+ pricing_info: Information used for calculating the cost of Ollama usage.
27
+ trace_content: Flag indicating whether to trace the actual content.
28
+
29
+ Returns:
30
+ A function that wraps the chat method to add telemetry.
31
+ """
32
+
33
+ async def wrapper(wrapped, instance, args, kwargs):
34
+ """
35
+ Wraps the 'chat' API call to add telemetry.
36
+
37
+ This collects metrics such as execution time, cost, and token usage, and handles errors
38
+ gracefully, adding details to the trace for observability.
39
+
40
+ Args:
41
+ wrapped: The original 'chat' method to be wrapped.
42
+ instance: The instance of the class where the original method is defined.
43
+ args: Positional arguments for the 'chat' method.
44
+ kwargs: Keyword arguments for the 'chat' method.
45
+
46
+ Returns:
47
+ The response from the original 'chat' method.
48
+ """
49
+
50
+ # Check if streaming is enabled for the API call
51
+ streaming = kwargs.get("stream", False)
52
+
53
+ # pylint: disable=no-else-return
54
+ if streaming:
55
+ # Special handling for streaming response to accommodate the nature of data flow
56
+ async def stream_generator():
57
+ with tracer.start_as_current_span(gen_ai_endpoint, kind= SpanKind.CLIENT) as span:
58
+ # Placeholder for aggregating streaming response
59
+ llmresponse = ""
60
+
61
+ # Loop through streaming events capturing relevant details
62
+ async for chunk in await wrapped(*args, **kwargs):
63
+ # Collect aggregated response from events
64
+ content = chunk['message']['content']
65
+ llmresponse += content
66
+
67
+ if chunk['done'] is True:
68
+ completion_tokens = chunk["eval_count"]
69
+
70
+ yield chunk
71
+
72
+ # Handling exception ensure observability without disrupting operation
73
+ try:
74
+ # Format 'messages' into a single string
75
+ message_prompt = kwargs.get("messages", "")
76
+ formatted_messages = []
77
+ for message in message_prompt:
78
+ role = message["role"]
79
+ content = message["content"]
80
+
81
+ if isinstance(content, list):
82
+ content_str = ", ".join(
83
+ # pylint: disable=line-too-long
84
+ f'{item["type"]}: {item["text"] if "text" in item else item["image_url"]}'
85
+ if "type" in item else f'text: {item["text"]}'
86
+ for item in content
87
+ )
88
+ formatted_messages.append(f"{role}: {content_str}")
89
+ else:
90
+ formatted_messages.append(f"{role}: {content}")
91
+ prompt = "\n".join(formatted_messages)
92
+
93
+ # Calculate cost of the operation
94
+ cost = 0
95
+ prompt_tokens = general_tokens(prompt)
96
+ total_tokens = prompt_tokens + completion_tokens
97
+
98
+ # Set Span attributes
99
+ span.set_attribute(TELEMETRY_SDK_NAME, "openlit")
100
+ span.set_attribute(SemanticConvetion.GEN_AI_SYSTEM,
101
+ SemanticConvetion.GEN_AI_SYSTEM_OLLAMA)
102
+ span.set_attribute(SemanticConvetion.GEN_AI_TYPE,
103
+ SemanticConvetion.GEN_AI_TYPE_CHAT)
104
+ span.set_attribute(SemanticConvetion.GEN_AI_ENDPOINT,
105
+ gen_ai_endpoint)
106
+ span.set_attribute(SemanticConvetion.GEN_AI_ENVIRONMENT,
107
+ environment)
108
+ span.set_attribute(SemanticConvetion.GEN_AI_APPLICATION_NAME,
109
+ application_name)
110
+ span.set_attribute(SemanticConvetion.GEN_AI_REQUEST_MODEL,
111
+ kwargs.get("model", "llama3"))
112
+ span.set_attribute(SemanticConvetion.GEN_AI_REQUEST_IS_STREAM,
113
+ True)
114
+ span.set_attribute(SemanticConvetion.GEN_AI_USAGE_PROMPT_TOKENS,
115
+ prompt_tokens)
116
+ span.set_attribute(SemanticConvetion.GEN_AI_USAGE_COMPLETION_TOKENS,
117
+ completion_tokens)
118
+ span.set_attribute(SemanticConvetion.GEN_AI_USAGE_TOTAL_TOKENS,
119
+ total_tokens)
120
+ span.set_attribute(SemanticConvetion.GEN_AI_USAGE_COST,
121
+ cost)
122
+ if trace_content:
123
+ span.set_attribute(SemanticConvetion.GEN_AI_CONTENT_PROMPT,
124
+ prompt)
125
+ span.set_attribute(SemanticConvetion.GEN_AI_CONTENT_COMPLETION,
126
+ llmresponse)
127
+
128
+ span.set_status(Status(StatusCode.OK))
129
+
130
+ if disable_metrics is False:
131
+ attributes = {
132
+ TELEMETRY_SDK_NAME:
133
+ "openlit",
134
+ SemanticConvetion.GEN_AI_APPLICATION_NAME:
135
+ application_name,
136
+ SemanticConvetion.GEN_AI_SYSTEM:
137
+ SemanticConvetion.GEN_AI_SYSTEM_OLLAMA,
138
+ SemanticConvetion.GEN_AI_ENVIRONMENT:
139
+ environment,
140
+ SemanticConvetion.GEN_AI_TYPE:
141
+ SemanticConvetion.GEN_AI_TYPE_CHAT,
142
+ SemanticConvetion.GEN_AI_REQUEST_MODEL:
143
+ kwargs.get("model", "llama3")
144
+ }
145
+
146
+ metrics["genai_requests"].add(1, attributes)
147
+ metrics["genai_total_tokens"].add(total_tokens, attributes)
148
+ metrics["genai_completion_tokens"].add(completion_tokens, attributes)
149
+ metrics["genai_prompt_tokens"].add(prompt_tokens, attributes)
150
+ metrics["genai_cost"].record(cost, attributes)
151
+
152
+ except Exception as e:
153
+ handle_exception(span, e)
154
+ logger.error("Error in trace creation: %s", e)
155
+
156
+ return stream_generator()
157
+
158
+ # Handling for non-streaming responses
159
+ else:
160
+ # pylint: disable=line-too-long
161
+ with tracer.start_as_current_span(gen_ai_endpoint, kind= SpanKind.CLIENT) as span:
162
+ response = await wrapped(*args, **kwargs)
163
+
164
+ try:
165
+ # Format 'messages' into a single string
166
+ message_prompt = kwargs.get("messages", "")
167
+ formatted_messages = []
168
+ for message in message_prompt:
169
+ role = message["role"]
170
+ content = message["content"]
171
+
172
+ if isinstance(content, list):
173
+ content_str = ", ".join(
174
+ # pylint: disable=line-too-long
175
+ f'{item["type"]}: {item["text"] if "text" in item else item["image_url"]}'
176
+ if "type" in item else f'text: {item["text"]}'
177
+ for item in content
178
+ )
179
+ formatted_messages.append(f"{role}: {content_str}")
180
+ else:
181
+ formatted_messages.append(f"{role}: {content}")
182
+ prompt = "\n".join(formatted_messages)
183
+
184
+ # Set base span attribues
185
+ span.set_attribute(TELEMETRY_SDK_NAME, "openlit")
186
+ span.set_attribute(SemanticConvetion.GEN_AI_SYSTEM,
187
+ SemanticConvetion.GEN_AI_SYSTEM_OLLAMA)
188
+ span.set_attribute(SemanticConvetion.GEN_AI_TYPE,
189
+ SemanticConvetion.GEN_AI_TYPE_CHAT)
190
+ span.set_attribute(SemanticConvetion.GEN_AI_ENDPOINT,
191
+ gen_ai_endpoint)
192
+ span.set_attribute(SemanticConvetion.GEN_AI_ENVIRONMENT,
193
+ environment)
194
+ span.set_attribute(SemanticConvetion.GEN_AI_APPLICATION_NAME,
195
+ application_name)
196
+ span.set_attribute(SemanticConvetion.GEN_AI_REQUEST_MODEL,
197
+ kwargs.get("model", "llama3"))
198
+ span.set_attribute(SemanticConvetion.GEN_AI_REQUEST_IS_STREAM,
199
+ False)
200
+ if trace_content:
201
+ span.set_attribute(SemanticConvetion.GEN_AI_CONTENT_PROMPT,
202
+ prompt)
203
+ span.set_attribute(SemanticConvetion.GEN_AI_CONTENT_COMPLETION,
204
+ response['message']['content'])
205
+
206
+ # Calculate cost of the operation
207
+ cost = 0
208
+ prompt_tokens = general_tokens(prompt)
209
+ completion_tokens = response["eval_count"]
210
+ total_tokens = prompt_tokens + completion_tokens
211
+
212
+ span.set_attribute(SemanticConvetion.GEN_AI_USAGE_PROMPT_TOKENS,
213
+ prompt_tokens)
214
+ span.set_attribute(SemanticConvetion.GEN_AI_USAGE_COMPLETION_TOKENS,
215
+ completion_tokens)
216
+ span.set_attribute(SemanticConvetion.GEN_AI_USAGE_TOTAL_TOKENS,
217
+ total_tokens)
218
+ span.set_attribute(SemanticConvetion.GEN_AI_RESPONSE_FINISH_REASON,
219
+ response["done_reason"])
220
+ span.set_attribute(SemanticConvetion.GEN_AI_USAGE_COST,
221
+ cost)
222
+
223
+ span.set_status(Status(StatusCode.OK))
224
+
225
+ if disable_metrics is False:
226
+ attributes = {
227
+ TELEMETRY_SDK_NAME:
228
+ "openlit",
229
+ SemanticConvetion.GEN_AI_APPLICATION_NAME:
230
+ application_name,
231
+ SemanticConvetion.GEN_AI_SYSTEM:
232
+ SemanticConvetion.GEN_AI_SYSTEM_OLLAMA,
233
+ SemanticConvetion.GEN_AI_ENVIRONMENT:
234
+ environment,
235
+ SemanticConvetion.GEN_AI_TYPE:
236
+ SemanticConvetion.GEN_AI_TYPE_CHAT,
237
+ SemanticConvetion.GEN_AI_REQUEST_MODEL:
238
+ kwargs.get("model", "llama3")
239
+ }
240
+
241
+ metrics["genai_requests"].add(1, attributes)
242
+ metrics["genai_total_tokens"].add(total_tokens, attributes)
243
+ metrics["genai_completion_tokens"].add(completion_tokens, attributes)
244
+ metrics["genai_prompt_tokens"].add(prompt_tokens, attributes)
245
+ metrics["genai_cost"].record(cost, attributes)
246
+
247
+ # Return original response
248
+ return response
249
+
250
+ except Exception as e:
251
+ handle_exception(span, e)
252
+ logger.error("Error in trace creation: %s", e)
253
+
254
+ # Return original response
255
+ return response
256
+
257
+ return wrapper
258
+
259
+ def async_generate(gen_ai_endpoint, version, environment, application_name,
260
+ tracer, pricing_info, trace_content, metrics, disable_metrics):
261
+ """
262
+ Generates a telemetry wrapper for generate to collect metrics.
263
+
264
+ Args:
265
+ gen_ai_endpoint: Endpoint identifier for logging and tracing.
266
+ version: Version of the monitoring package.
267
+ environment: Deployment environment (e.g., production, staging).
268
+ application_name: Name of the application using the Ollama API.
269
+ tracer: OpenTelemetry tracer for creating spans.
270
+ pricing_info: Information used for calculating the cost of Ollama usage.
271
+ trace_content: Flag indicating whether to trace the actual content.
272
+
273
+ Returns:
274
+ A function that wraps the generate method to add telemetry.
275
+ """
276
+
277
+ async def wrapper(wrapped, instance, args, kwargs):
278
+ """
279
+ Wraps the 'generate' API call to add telemetry.
280
+
281
+ This collects metrics such as execution time, cost, and token usage, and handles errors
282
+ gracefully, adding details to the trace for observability.
283
+
284
+ Args:
285
+ wrapped: The original 'generate' method to be wrapped.
286
+ instance: The instance of the class where the original method is defined.
287
+ args: Positional arguments for the 'generate' method.
288
+ kwargs: Keyword arguments for the 'generate' method.
289
+
290
+ Returns:
291
+ The response from the original 'generate' method.
292
+ """
293
+
294
+ # Check if streaming is enabled for the API call
295
+ streaming = kwargs.get("stream", False)
296
+
297
+ # pylint: disable=no-else-return
298
+ if streaming:
299
+ # Special handling for streaming response to accommodate the nature of data flow
300
+ async def stream_generator():
301
+ with tracer.start_as_current_span(gen_ai_endpoint, kind= SpanKind.CLIENT) as span:
302
+ # Placeholder for aggregating streaming response
303
+ llmresponse = ""
304
+
305
+ # Loop through streaming events capturing relevant details
306
+ async for chunk in await wrapped(*args, **kwargs):
307
+ # Collect aggregated response from events
308
+ content = chunk['response']
309
+ llmresponse += content
310
+
311
+ if chunk['done'] is True:
312
+ completion_tokens = chunk["eval_count"]
313
+
314
+ yield chunk
315
+
316
+ # Handling exception ensure observability without disrupting operation
317
+ try:
318
+ # Calculate cost of the operation
319
+ cost = 0
320
+ prompt_tokens = general_tokens(kwargs.get("prompt", ""))
321
+ total_tokens = prompt_tokens + completion_tokens
322
+
323
+ # Set Span attributes
324
+ span.set_attribute(TELEMETRY_SDK_NAME, "openlit")
325
+ span.set_attribute(SemanticConvetion.GEN_AI_SYSTEM,
326
+ SemanticConvetion.GEN_AI_SYSTEM_OLLAMA)
327
+ span.set_attribute(SemanticConvetion.GEN_AI_TYPE,
328
+ SemanticConvetion.GEN_AI_TYPE_CHAT)
329
+ span.set_attribute(SemanticConvetion.GEN_AI_ENDPOINT,
330
+ gen_ai_endpoint)
331
+ span.set_attribute(SemanticConvetion.GEN_AI_ENVIRONMENT,
332
+ environment)
333
+ span.set_attribute(SemanticConvetion.GEN_AI_APPLICATION_NAME,
334
+ application_name)
335
+ span.set_attribute(SemanticConvetion.GEN_AI_REQUEST_MODEL,
336
+ kwargs.get("model", "llama3"))
337
+ span.set_attribute(SemanticConvetion.GEN_AI_REQUEST_IS_STREAM,
338
+ True)
339
+ span.set_attribute(SemanticConvetion.GEN_AI_USAGE_PROMPT_TOKENS,
340
+ prompt_tokens)
341
+ span.set_attribute(SemanticConvetion.GEN_AI_USAGE_COMPLETION_TOKENS,
342
+ completion_tokens)
343
+ span.set_attribute(SemanticConvetion.GEN_AI_USAGE_TOTAL_TOKENS,
344
+ total_tokens)
345
+ span.set_attribute(SemanticConvetion.GEN_AI_USAGE_COST,
346
+ cost)
347
+ if trace_content:
348
+ span.set_attribute(SemanticConvetion.GEN_AI_CONTENT_PROMPT,
349
+ kwargs.get("prompt", ""))
350
+ span.set_attribute(SemanticConvetion.GEN_AI_CONTENT_COMPLETION,
351
+ llmresponse)
352
+
353
+ span.set_status(Status(StatusCode.OK))
354
+
355
+ if disable_metrics is False:
356
+ attributes = {
357
+ TELEMETRY_SDK_NAME:
358
+ "openlit",
359
+ SemanticConvetion.GEN_AI_APPLICATION_NAME:
360
+ application_name,
361
+ SemanticConvetion.GEN_AI_SYSTEM:
362
+ SemanticConvetion.GEN_AI_SYSTEM_OLLAMA,
363
+ SemanticConvetion.GEN_AI_ENVIRONMENT:
364
+ environment,
365
+ SemanticConvetion.GEN_AI_TYPE:
366
+ SemanticConvetion.GEN_AI_TYPE_CHAT,
367
+ SemanticConvetion.GEN_AI_REQUEST_MODEL:
368
+ kwargs.get("model", "llama3")
369
+ }
370
+
371
+ metrics["genai_requests"].add(1, attributes)
372
+ metrics["genai_total_tokens"].add(total_tokens, attributes)
373
+ metrics["genai_completion_tokens"].add(completion_tokens, attributes)
374
+ metrics["genai_prompt_tokens"].add(prompt_tokens, attributes)
375
+ metrics["genai_cost"].record(cost, attributes)
376
+
377
+ except Exception as e:
378
+ handle_exception(span, e)
379
+ logger.error("Error in trace creation: %s", e)
380
+
381
+ return stream_generator()
382
+
383
+ # Handling for non-streaming responses
384
+ else:
385
+ # pylint: disable=line-too-long
386
+ with tracer.start_as_current_span(gen_ai_endpoint, kind= SpanKind.CLIENT) as span:
387
+ response = await wrapped(*args, **kwargs)
388
+
389
+ try:
390
+ # Set base span attribues
391
+ span.set_attribute(TELEMETRY_SDK_NAME, "openlit")
392
+ span.set_attribute(SemanticConvetion.GEN_AI_SYSTEM,
393
+ SemanticConvetion.GEN_AI_SYSTEM_OLLAMA)
394
+ span.set_attribute(SemanticConvetion.GEN_AI_TYPE,
395
+ SemanticConvetion.GEN_AI_TYPE_CHAT)
396
+ span.set_attribute(SemanticConvetion.GEN_AI_ENDPOINT,
397
+ gen_ai_endpoint)
398
+ span.set_attribute(SemanticConvetion.GEN_AI_ENVIRONMENT,
399
+ environment)
400
+ span.set_attribute(SemanticConvetion.GEN_AI_APPLICATION_NAME,
401
+ application_name)
402
+ span.set_attribute(SemanticConvetion.GEN_AI_REQUEST_MODEL,
403
+ kwargs.get("model", "llama3"))
404
+ span.set_attribute(SemanticConvetion.GEN_AI_REQUEST_IS_STREAM,
405
+ False)
406
+ if trace_content:
407
+ span.set_attribute(SemanticConvetion.GEN_AI_CONTENT_PROMPT,
408
+ kwargs.get("prompt", ""))
409
+ span.set_attribute(SemanticConvetion.GEN_AI_CONTENT_COMPLETION,
410
+ response['response'])
411
+
412
+ # Calculate cost of the operation
413
+ cost = 0
414
+ prompt_tokens = response["prompt_eval_count"]
415
+ completion_tokens = response["eval_count"]
416
+ total_tokens = prompt_tokens + completion_tokens
417
+
418
+ span.set_attribute(SemanticConvetion.GEN_AI_USAGE_PROMPT_TOKENS,
419
+ prompt_tokens)
420
+ span.set_attribute(SemanticConvetion.GEN_AI_USAGE_COMPLETION_TOKENS,
421
+ completion_tokens)
422
+ span.set_attribute(SemanticConvetion.GEN_AI_USAGE_TOTAL_TOKENS,
423
+ total_tokens)
424
+ span.set_attribute(SemanticConvetion.GEN_AI_RESPONSE_FINISH_REASON,
425
+ response["done_reason"])
426
+ span.set_attribute(SemanticConvetion.GEN_AI_USAGE_COST,
427
+ cost)
428
+
429
+ span.set_status(Status(StatusCode.OK))
430
+
431
+ if disable_metrics is False:
432
+ attributes = {
433
+ TELEMETRY_SDK_NAME:
434
+ "openlit",
435
+ SemanticConvetion.GEN_AI_APPLICATION_NAME:
436
+ application_name,
437
+ SemanticConvetion.GEN_AI_SYSTEM:
438
+ SemanticConvetion.GEN_AI_SYSTEM_OLLAMA,
439
+ SemanticConvetion.GEN_AI_ENVIRONMENT:
440
+ environment,
441
+ SemanticConvetion.GEN_AI_TYPE:
442
+ SemanticConvetion.GEN_AI_TYPE_CHAT,
443
+ SemanticConvetion.GEN_AI_REQUEST_MODEL:
444
+ kwargs.get("model", "llama3")
445
+ }
446
+
447
+ metrics["genai_requests"].add(1, attributes)
448
+ metrics["genai_total_tokens"].add(total_tokens, attributes)
449
+ metrics["genai_completion_tokens"].add(completion_tokens, attributes)
450
+ metrics["genai_prompt_tokens"].add(prompt_tokens, attributes)
451
+ metrics["genai_cost"].record(cost, attributes)
452
+
453
+ # Return original response
454
+ return response
455
+
456
+ except Exception as e:
457
+ handle_exception(span, e)
458
+ logger.error("Error in trace creation: %s", e)
459
+
460
+ # Return original response
461
+ return response
462
+
463
+ return wrapper
464
+
465
+ def async_embeddings(gen_ai_endpoint, version, environment, application_name,
466
+ tracer, pricing_info, trace_content, metrics, disable_metrics):
467
+ """
468
+ Generates a telemetry wrapper for embeddings to collect metrics.
469
+
470
+ Args:
471
+ gen_ai_endpoint: Endpoint identifier for logging and tracing.
472
+ version: Version of the monitoring package.
473
+ environment: Deployment environment (e.g., production, staging).
474
+ application_name: Name of the application using the Ollama API.
475
+ tracer: OpenTelemetry tracer for creating spans.
476
+ pricing_info: Information used for calculating the cost of Ollama usage.
477
+ trace_content: Flag indicating whether to trace the actual content.
478
+
479
+ Returns:
480
+ A function that wraps the embeddings method to add telemetry.
481
+ """
482
+
483
+ async def wrapper(wrapped, instance, args, kwargs):
484
+ """
485
+ Wraps the 'embeddings' API call to add telemetry.
486
+
487
+ This collects metrics such as execution time, cost, and token usage, and handles errors
488
+ gracefully, adding details to the trace for observability.
489
+
490
+ Args:
491
+ wrapped: The original 'embeddings' method to be wrapped.
492
+ instance: The instance of the class where the original method is defined.
493
+ args: Positional arguments for the 'embeddings' method.
494
+ kwargs: Keyword arguments for the 'embeddings' method.
495
+
496
+ Returns:
497
+ The response from the original 'embeddings' method.
498
+ """
499
+
500
+ with tracer.start_as_current_span(gen_ai_endpoint, kind= SpanKind.CLIENT) as span:
501
+ response = await wrapped(*args, **kwargs)
502
+
503
+ try:
504
+ # Calculate cost of the operation
505
+ cost = 0
506
+ prompt_tokens = general_tokens(kwargs.get('prompt', ""))
507
+ # Set Span attributes
508
+ span.set_attribute(TELEMETRY_SDK_NAME, "openlit")
509
+ span.set_attribute(SemanticConvetion.GEN_AI_SYSTEM,
510
+ SemanticConvetion.GEN_AI_SYSTEM_OLLAMA)
511
+ span.set_attribute(SemanticConvetion.GEN_AI_TYPE,
512
+ SemanticConvetion.GEN_AI_TYPE_EMBEDDING)
513
+ span.set_attribute(SemanticConvetion.GEN_AI_ENDPOINT,
514
+ gen_ai_endpoint)
515
+ span.set_attribute(SemanticConvetion.GEN_AI_ENVIRONMENT,
516
+ environment)
517
+ span.set_attribute(SemanticConvetion.GEN_AI_APPLICATION_NAME,
518
+ application_name)
519
+ span.set_attribute(SemanticConvetion.GEN_AI_REQUEST_MODEL,
520
+ kwargs.get('model', "llama3"))
521
+ span.set_attribute(SemanticConvetion.GEN_AI_USAGE_PROMPT_TOKENS,
522
+ prompt_tokens)
523
+ span.set_attribute(SemanticConvetion.GEN_AI_USAGE_TOTAL_TOKENS,
524
+ prompt_tokens)
525
+ span.set_attribute(SemanticConvetion.GEN_AI_USAGE_COST,
526
+ cost)
527
+ if trace_content:
528
+ span.set_attribute(SemanticConvetion.GEN_AI_CONTENT_PROMPT,
529
+ kwargs.get('prompt', ""))
530
+
531
+ span.set_status(Status(StatusCode.OK))
532
+
533
+ if disable_metrics is False:
534
+ attributes = {
535
+ TELEMETRY_SDK_NAME:
536
+ "openlit",
537
+ SemanticConvetion.GEN_AI_APPLICATION_NAME:
538
+ application_name,
539
+ SemanticConvetion.GEN_AI_SYSTEM:
540
+ SemanticConvetion.GEN_AI_SYSTEM_OLLAMA,
541
+ SemanticConvetion.GEN_AI_ENVIRONMENT:
542
+ environment,
543
+ SemanticConvetion.GEN_AI_TYPE:
544
+ SemanticConvetion.GEN_AI_TYPE_EMBEDDING,
545
+ SemanticConvetion.GEN_AI_REQUEST_MODEL:
546
+ kwargs.get('model', "llama3")
547
+ }
548
+
549
+ metrics["genai_requests"].add(1, attributes)
550
+ metrics["genai_total_tokens"].add(prompt_tokens, attributes)
551
+ metrics["genai_prompt_tokens"].add(prompt_tokens, attributes)
552
+ metrics["genai_cost"].record(cost, attributes)
553
+
554
+ # Return original response
555
+ return response
556
+
557
+ except Exception as e:
558
+ handle_exception(span, e)
559
+ logger.error("Error in trace creation: %s", e)
560
+
561
+ # Return original response
562
+ return response
563
+
564
+ return wrapper
@@ -0,0 +1,564 @@
1
+ # pylint: disable=duplicate-code, broad-exception-caught, too-many-statements, unused-argument, possibly-used-before-assignment
2
+ """
3
+ Module for monitoring Ollama API 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 handle_exception, general_tokens
10
+ from openlit.semcov import SemanticConvetion
11
+
12
+ # Initialize logger for logging potential issues and operations
13
+ logger = logging.getLogger(__name__)
14
+
15
+ def chat(gen_ai_endpoint, version, environment, application_name,
16
+ tracer, pricing_info, trace_content, metrics, disable_metrics):
17
+ """
18
+ Generates a telemetry wrapper for chat to collect metrics.
19
+
20
+ Args:
21
+ gen_ai_endpoint: Endpoint identifier for logging and tracing.
22
+ version: Version of the monitoring package.
23
+ environment: Deployment environment (e.g., production, staging).
24
+ application_name: Name of the application using the Ollama API.
25
+ tracer: OpenTelemetry tracer for creating spans.
26
+ pricing_info: Information used for calculating the cost of Ollama usage.
27
+ trace_content: Flag indicating whether to trace the actual content.
28
+
29
+ Returns:
30
+ A function that wraps the chat method to add telemetry.
31
+ """
32
+
33
+ def wrapper(wrapped, instance, args, kwargs):
34
+ """
35
+ Wraps the 'chat' API call to add telemetry.
36
+
37
+ This collects metrics such as execution time, cost, and token usage, and handles errors
38
+ gracefully, adding details to the trace for observability.
39
+
40
+ Args:
41
+ wrapped: The original 'chat' method to be wrapped.
42
+ instance: The instance of the class where the original method is defined.
43
+ args: Positional arguments for the 'chat' method.
44
+ kwargs: Keyword arguments for the 'chat' method.
45
+
46
+ Returns:
47
+ The response from the original 'chat' method.
48
+ """
49
+
50
+ # Check if streaming is enabled for the API call
51
+ streaming = kwargs.get("stream", False)
52
+
53
+ # pylint: disable=no-else-return
54
+ if streaming:
55
+ # Special handling for streaming response to accommodate the nature of data flow
56
+ def stream_generator():
57
+ with tracer.start_as_current_span(gen_ai_endpoint, kind= SpanKind.CLIENT) as span:
58
+ # Placeholder for aggregating streaming response
59
+ llmresponse = ""
60
+
61
+ # Loop through streaming events capturing relevant details
62
+ for chunk in wrapped(*args, **kwargs):
63
+ # Collect aggregated response from events
64
+ content = chunk['message']['content']
65
+ llmresponse += content
66
+
67
+ if chunk['done'] is True:
68
+ completion_tokens = chunk["eval_count"]
69
+
70
+ yield chunk
71
+
72
+ # Handling exception ensure observability without disrupting operation
73
+ try:
74
+ # Format 'messages' into a single string
75
+ message_prompt = kwargs.get("messages", "")
76
+ formatted_messages = []
77
+ for message in message_prompt:
78
+ role = message["role"]
79
+ content = message["content"]
80
+
81
+ if isinstance(content, list):
82
+ content_str = ", ".join(
83
+ # pylint: disable=line-too-long
84
+ f'{item["type"]}: {item["text"] if "text" in item else item["image_url"]}'
85
+ if "type" in item else f'text: {item["text"]}'
86
+ for item in content
87
+ )
88
+ formatted_messages.append(f"{role}: {content_str}")
89
+ else:
90
+ formatted_messages.append(f"{role}: {content}")
91
+ prompt = "\n".join(formatted_messages)
92
+
93
+ # Calculate cost of the operation
94
+ cost = 0
95
+ prompt_tokens = general_tokens(prompt)
96
+ total_tokens = prompt_tokens + completion_tokens
97
+
98
+ # Set Span attributes
99
+ span.set_attribute(TELEMETRY_SDK_NAME, "openlit")
100
+ span.set_attribute(SemanticConvetion.GEN_AI_SYSTEM,
101
+ SemanticConvetion.GEN_AI_SYSTEM_OLLAMA)
102
+ span.set_attribute(SemanticConvetion.GEN_AI_TYPE,
103
+ SemanticConvetion.GEN_AI_TYPE_CHAT)
104
+ span.set_attribute(SemanticConvetion.GEN_AI_ENDPOINT,
105
+ gen_ai_endpoint)
106
+ span.set_attribute(SemanticConvetion.GEN_AI_ENVIRONMENT,
107
+ environment)
108
+ span.set_attribute(SemanticConvetion.GEN_AI_APPLICATION_NAME,
109
+ application_name)
110
+ span.set_attribute(SemanticConvetion.GEN_AI_REQUEST_MODEL,
111
+ kwargs.get("model", "llama3"))
112
+ span.set_attribute(SemanticConvetion.GEN_AI_REQUEST_IS_STREAM,
113
+ True)
114
+ span.set_attribute(SemanticConvetion.GEN_AI_USAGE_PROMPT_TOKENS,
115
+ prompt_tokens)
116
+ span.set_attribute(SemanticConvetion.GEN_AI_USAGE_COMPLETION_TOKENS,
117
+ completion_tokens)
118
+ span.set_attribute(SemanticConvetion.GEN_AI_USAGE_TOTAL_TOKENS,
119
+ total_tokens)
120
+ span.set_attribute(SemanticConvetion.GEN_AI_USAGE_COST,
121
+ cost)
122
+ if trace_content:
123
+ span.set_attribute(SemanticConvetion.GEN_AI_CONTENT_PROMPT,
124
+ prompt)
125
+ span.set_attribute(SemanticConvetion.GEN_AI_CONTENT_COMPLETION,
126
+ llmresponse)
127
+
128
+ span.set_status(Status(StatusCode.OK))
129
+
130
+ if disable_metrics is False:
131
+ attributes = {
132
+ TELEMETRY_SDK_NAME:
133
+ "openlit",
134
+ SemanticConvetion.GEN_AI_APPLICATION_NAME:
135
+ application_name,
136
+ SemanticConvetion.GEN_AI_SYSTEM:
137
+ SemanticConvetion.GEN_AI_SYSTEM_OLLAMA,
138
+ SemanticConvetion.GEN_AI_ENVIRONMENT:
139
+ environment,
140
+ SemanticConvetion.GEN_AI_TYPE:
141
+ SemanticConvetion.GEN_AI_TYPE_CHAT,
142
+ SemanticConvetion.GEN_AI_REQUEST_MODEL:
143
+ kwargs.get("model", "llama3")
144
+ }
145
+
146
+ metrics["genai_requests"].add(1, attributes)
147
+ metrics["genai_total_tokens"].add(total_tokens, attributes)
148
+ metrics["genai_completion_tokens"].add(completion_tokens, attributes)
149
+ metrics["genai_prompt_tokens"].add(prompt_tokens, attributes)
150
+ metrics["genai_cost"].record(cost, attributes)
151
+
152
+ except Exception as e:
153
+ handle_exception(span, e)
154
+ logger.error("Error in trace creation: %s", e)
155
+
156
+ return stream_generator()
157
+
158
+ # Handling for non-streaming responses
159
+ else:
160
+ # pylint: disable=line-too-long
161
+ with tracer.start_as_current_span(gen_ai_endpoint, kind= SpanKind.CLIENT) as span:
162
+ response = wrapped(*args, **kwargs)
163
+
164
+ try:
165
+ # Format 'messages' into a single string
166
+ message_prompt = kwargs.get("messages", "")
167
+ formatted_messages = []
168
+ for message in message_prompt:
169
+ role = message["role"]
170
+ content = message["content"]
171
+
172
+ if isinstance(content, list):
173
+ content_str = ", ".join(
174
+ # pylint: disable=line-too-long
175
+ f'{item["type"]}: {item["text"] if "text" in item else item["image_url"]}'
176
+ if "type" in item else f'text: {item["text"]}'
177
+ for item in content
178
+ )
179
+ formatted_messages.append(f"{role}: {content_str}")
180
+ else:
181
+ formatted_messages.append(f"{role}: {content}")
182
+ prompt = "\n".join(formatted_messages)
183
+
184
+ # Set base span attribues
185
+ span.set_attribute(TELEMETRY_SDK_NAME, "openlit")
186
+ span.set_attribute(SemanticConvetion.GEN_AI_SYSTEM,
187
+ SemanticConvetion.GEN_AI_SYSTEM_OLLAMA)
188
+ span.set_attribute(SemanticConvetion.GEN_AI_TYPE,
189
+ SemanticConvetion.GEN_AI_TYPE_CHAT)
190
+ span.set_attribute(SemanticConvetion.GEN_AI_ENDPOINT,
191
+ gen_ai_endpoint)
192
+ span.set_attribute(SemanticConvetion.GEN_AI_ENVIRONMENT,
193
+ environment)
194
+ span.set_attribute(SemanticConvetion.GEN_AI_APPLICATION_NAME,
195
+ application_name)
196
+ span.set_attribute(SemanticConvetion.GEN_AI_REQUEST_MODEL,
197
+ kwargs.get("model", "llama3"))
198
+ span.set_attribute(SemanticConvetion.GEN_AI_REQUEST_IS_STREAM,
199
+ False)
200
+ if trace_content:
201
+ span.set_attribute(SemanticConvetion.GEN_AI_CONTENT_PROMPT,
202
+ prompt)
203
+ span.set_attribute(SemanticConvetion.GEN_AI_CONTENT_COMPLETION,
204
+ response['message']['content'])
205
+
206
+ # Calculate cost of the operation
207
+ cost = 0
208
+ prompt_tokens = general_tokens(prompt)
209
+ completion_tokens = response["eval_count"]
210
+ total_tokens = prompt_tokens + completion_tokens
211
+
212
+ span.set_attribute(SemanticConvetion.GEN_AI_USAGE_PROMPT_TOKENS,
213
+ prompt_tokens)
214
+ span.set_attribute(SemanticConvetion.GEN_AI_USAGE_COMPLETION_TOKENS,
215
+ completion_tokens)
216
+ span.set_attribute(SemanticConvetion.GEN_AI_USAGE_TOTAL_TOKENS,
217
+ total_tokens)
218
+ span.set_attribute(SemanticConvetion.GEN_AI_RESPONSE_FINISH_REASON,
219
+ response["done_reason"])
220
+ span.set_attribute(SemanticConvetion.GEN_AI_USAGE_COST,
221
+ cost)
222
+
223
+ span.set_status(Status(StatusCode.OK))
224
+
225
+ if disable_metrics is False:
226
+ attributes = {
227
+ TELEMETRY_SDK_NAME:
228
+ "openlit",
229
+ SemanticConvetion.GEN_AI_APPLICATION_NAME:
230
+ application_name,
231
+ SemanticConvetion.GEN_AI_SYSTEM:
232
+ SemanticConvetion.GEN_AI_SYSTEM_OLLAMA,
233
+ SemanticConvetion.GEN_AI_ENVIRONMENT:
234
+ environment,
235
+ SemanticConvetion.GEN_AI_TYPE:
236
+ SemanticConvetion.GEN_AI_TYPE_CHAT,
237
+ SemanticConvetion.GEN_AI_REQUEST_MODEL:
238
+ kwargs.get("model", "llama3")
239
+ }
240
+
241
+ metrics["genai_requests"].add(1, attributes)
242
+ metrics["genai_total_tokens"].add(total_tokens, attributes)
243
+ metrics["genai_completion_tokens"].add(completion_tokens, attributes)
244
+ metrics["genai_prompt_tokens"].add(prompt_tokens, attributes)
245
+ metrics["genai_cost"].record(cost, attributes)
246
+
247
+ # Return original response
248
+ return response
249
+
250
+ except Exception as e:
251
+ handle_exception(span, e)
252
+ logger.error("Error in trace creation: %s", e)
253
+
254
+ # Return original response
255
+ return response
256
+
257
+ return wrapper
258
+
259
+ def generate(gen_ai_endpoint, version, environment, application_name,
260
+ tracer, pricing_info, trace_content, metrics, disable_metrics):
261
+ """
262
+ Generates a telemetry wrapper for generate to collect metrics.
263
+
264
+ Args:
265
+ gen_ai_endpoint: Endpoint identifier for logging and tracing.
266
+ version: Version of the monitoring package.
267
+ environment: Deployment environment (e.g., production, staging).
268
+ application_name: Name of the application using the Ollama API.
269
+ tracer: OpenTelemetry tracer for creating spans.
270
+ pricing_info: Information used for calculating the cost of Ollama usage.
271
+ trace_content: Flag indicating whether to trace the actual content.
272
+
273
+ Returns:
274
+ A function that wraps the generate method to add telemetry.
275
+ """
276
+
277
+ def wrapper(wrapped, instance, args, kwargs):
278
+ """
279
+ Wraps the 'generate' API call to add telemetry.
280
+
281
+ This collects metrics such as execution time, cost, and token usage, and handles errors
282
+ gracefully, adding details to the trace for observability.
283
+
284
+ Args:
285
+ wrapped: The original 'generate' method to be wrapped.
286
+ instance: The instance of the class where the original method is defined.
287
+ args: Positional arguments for the 'generate' method.
288
+ kwargs: Keyword arguments for the 'generate' method.
289
+
290
+ Returns:
291
+ The response from the original 'generate' method.
292
+ """
293
+
294
+ # Check if streaming is enabled for the API call
295
+ streaming = kwargs.get("stream", False)
296
+
297
+ # pylint: disable=no-else-return
298
+ if streaming:
299
+ # Special handling for streaming response to accommodate the nature of data flow
300
+ def stream_generator():
301
+ with tracer.start_as_current_span(gen_ai_endpoint, kind= SpanKind.CLIENT) as span:
302
+ # Placeholder for aggregating streaming response
303
+ llmresponse = ""
304
+
305
+ # Loop through streaming events capturing relevant details
306
+ for chunk in wrapped(*args, **kwargs):
307
+ # Collect aggregated response from events
308
+ content = chunk['response']
309
+ llmresponse += content
310
+
311
+ if chunk['done'] is True:
312
+ completion_tokens = chunk["eval_count"]
313
+
314
+ yield chunk
315
+
316
+ # Handling exception ensure observability without disrupting operation
317
+ try:
318
+ # Calculate cost of the operation
319
+ cost = 0
320
+ prompt_tokens = general_tokens(kwargs.get("prompt", ""))
321
+ total_tokens = prompt_tokens + completion_tokens
322
+
323
+ # Set Span attributes
324
+ span.set_attribute(TELEMETRY_SDK_NAME, "openlit")
325
+ span.set_attribute(SemanticConvetion.GEN_AI_SYSTEM,
326
+ SemanticConvetion.GEN_AI_SYSTEM_OLLAMA)
327
+ span.set_attribute(SemanticConvetion.GEN_AI_TYPE,
328
+ SemanticConvetion.GEN_AI_TYPE_CHAT)
329
+ span.set_attribute(SemanticConvetion.GEN_AI_ENDPOINT,
330
+ gen_ai_endpoint)
331
+ span.set_attribute(SemanticConvetion.GEN_AI_ENVIRONMENT,
332
+ environment)
333
+ span.set_attribute(SemanticConvetion.GEN_AI_APPLICATION_NAME,
334
+ application_name)
335
+ span.set_attribute(SemanticConvetion.GEN_AI_REQUEST_MODEL,
336
+ kwargs.get("model", "llama3"))
337
+ span.set_attribute(SemanticConvetion.GEN_AI_REQUEST_IS_STREAM,
338
+ True)
339
+ span.set_attribute(SemanticConvetion.GEN_AI_USAGE_PROMPT_TOKENS,
340
+ prompt_tokens)
341
+ span.set_attribute(SemanticConvetion.GEN_AI_USAGE_COMPLETION_TOKENS,
342
+ completion_tokens)
343
+ span.set_attribute(SemanticConvetion.GEN_AI_USAGE_TOTAL_TOKENS,
344
+ total_tokens)
345
+ span.set_attribute(SemanticConvetion.GEN_AI_USAGE_COST,
346
+ cost)
347
+ if trace_content:
348
+ span.set_attribute(SemanticConvetion.GEN_AI_CONTENT_PROMPT,
349
+ kwargs.get("prompt", ""))
350
+ span.set_attribute(SemanticConvetion.GEN_AI_CONTENT_COMPLETION,
351
+ llmresponse)
352
+
353
+ span.set_status(Status(StatusCode.OK))
354
+
355
+ if disable_metrics is False:
356
+ attributes = {
357
+ TELEMETRY_SDK_NAME:
358
+ "openlit",
359
+ SemanticConvetion.GEN_AI_APPLICATION_NAME:
360
+ application_name,
361
+ SemanticConvetion.GEN_AI_SYSTEM:
362
+ SemanticConvetion.GEN_AI_SYSTEM_OLLAMA,
363
+ SemanticConvetion.GEN_AI_ENVIRONMENT:
364
+ environment,
365
+ SemanticConvetion.GEN_AI_TYPE:
366
+ SemanticConvetion.GEN_AI_TYPE_CHAT,
367
+ SemanticConvetion.GEN_AI_REQUEST_MODEL:
368
+ kwargs.get("model", "llama3")
369
+ }
370
+
371
+ metrics["genai_requests"].add(1, attributes)
372
+ metrics["genai_total_tokens"].add(total_tokens, attributes)
373
+ metrics["genai_completion_tokens"].add(completion_tokens, attributes)
374
+ metrics["genai_prompt_tokens"].add(prompt_tokens, attributes)
375
+ metrics["genai_cost"].record(cost, attributes)
376
+
377
+ except Exception as e:
378
+ handle_exception(span, e)
379
+ logger.error("Error in trace creation: %s", e)
380
+
381
+ return stream_generator()
382
+
383
+ # Handling for non-streaming responses
384
+ else:
385
+ # pylint: disable=line-too-long
386
+ with tracer.start_as_current_span(gen_ai_endpoint, kind= SpanKind.CLIENT) as span:
387
+ response = wrapped(*args, **kwargs)
388
+
389
+ try:
390
+ # Set base span attribues
391
+ span.set_attribute(TELEMETRY_SDK_NAME, "openlit")
392
+ span.set_attribute(SemanticConvetion.GEN_AI_SYSTEM,
393
+ SemanticConvetion.GEN_AI_SYSTEM_OLLAMA)
394
+ span.set_attribute(SemanticConvetion.GEN_AI_TYPE,
395
+ SemanticConvetion.GEN_AI_TYPE_CHAT)
396
+ span.set_attribute(SemanticConvetion.GEN_AI_ENDPOINT,
397
+ gen_ai_endpoint)
398
+ span.set_attribute(SemanticConvetion.GEN_AI_ENVIRONMENT,
399
+ environment)
400
+ span.set_attribute(SemanticConvetion.GEN_AI_APPLICATION_NAME,
401
+ application_name)
402
+ span.set_attribute(SemanticConvetion.GEN_AI_REQUEST_MODEL,
403
+ kwargs.get("model", "llama3"))
404
+ span.set_attribute(SemanticConvetion.GEN_AI_REQUEST_IS_STREAM,
405
+ False)
406
+ if trace_content:
407
+ span.set_attribute(SemanticConvetion.GEN_AI_CONTENT_PROMPT,
408
+ kwargs.get("prompt", ""))
409
+ span.set_attribute(SemanticConvetion.GEN_AI_CONTENT_COMPLETION,
410
+ response['response'])
411
+
412
+ # Calculate cost of the operation
413
+ cost = 0
414
+ prompt_tokens = response["prompt_eval_count"]
415
+ completion_tokens = response["eval_count"]
416
+ total_tokens = prompt_tokens + completion_tokens
417
+
418
+ span.set_attribute(SemanticConvetion.GEN_AI_USAGE_PROMPT_TOKENS,
419
+ prompt_tokens)
420
+ span.set_attribute(SemanticConvetion.GEN_AI_USAGE_COMPLETION_TOKENS,
421
+ completion_tokens)
422
+ span.set_attribute(SemanticConvetion.GEN_AI_USAGE_TOTAL_TOKENS,
423
+ total_tokens)
424
+ span.set_attribute(SemanticConvetion.GEN_AI_RESPONSE_FINISH_REASON,
425
+ response["done_reason"])
426
+ span.set_attribute(SemanticConvetion.GEN_AI_USAGE_COST,
427
+ cost)
428
+
429
+ span.set_status(Status(StatusCode.OK))
430
+
431
+ if disable_metrics is False:
432
+ attributes = {
433
+ TELEMETRY_SDK_NAME:
434
+ "openlit",
435
+ SemanticConvetion.GEN_AI_APPLICATION_NAME:
436
+ application_name,
437
+ SemanticConvetion.GEN_AI_SYSTEM:
438
+ SemanticConvetion.GEN_AI_SYSTEM_OLLAMA,
439
+ SemanticConvetion.GEN_AI_ENVIRONMENT:
440
+ environment,
441
+ SemanticConvetion.GEN_AI_TYPE:
442
+ SemanticConvetion.GEN_AI_TYPE_CHAT,
443
+ SemanticConvetion.GEN_AI_REQUEST_MODEL:
444
+ kwargs.get("model", "llama3")
445
+ }
446
+
447
+ metrics["genai_requests"].add(1, attributes)
448
+ metrics["genai_total_tokens"].add(total_tokens, attributes)
449
+ metrics["genai_completion_tokens"].add(completion_tokens, attributes)
450
+ metrics["genai_prompt_tokens"].add(prompt_tokens, attributes)
451
+ metrics["genai_cost"].record(cost, attributes)
452
+
453
+ # Return original response
454
+ return response
455
+
456
+ except Exception as e:
457
+ handle_exception(span, e)
458
+ logger.error("Error in trace creation: %s", e)
459
+
460
+ # Return original response
461
+ return response
462
+
463
+ return wrapper
464
+
465
+ def embeddings(gen_ai_endpoint, version, environment, application_name,
466
+ tracer, pricing_info, trace_content, metrics, disable_metrics):
467
+ """
468
+ Generates a telemetry wrapper for embeddings to collect metrics.
469
+
470
+ Args:
471
+ gen_ai_endpoint: Endpoint identifier for logging and tracing.
472
+ version: Version of the monitoring package.
473
+ environment: Deployment environment (e.g., production, staging).
474
+ application_name: Name of the application using the Ollama API.
475
+ tracer: OpenTelemetry tracer for creating spans.
476
+ pricing_info: Information used for calculating the cost of Ollama usage.
477
+ trace_content: Flag indicating whether to trace the actual content.
478
+
479
+ Returns:
480
+ A function that wraps the embeddings method to add telemetry.
481
+ """
482
+
483
+ def wrapper(wrapped, instance, args, kwargs):
484
+ """
485
+ Wraps the 'embeddings' API call to add telemetry.
486
+
487
+ This collects metrics such as execution time, cost, and token usage, and handles errors
488
+ gracefully, adding details to the trace for observability.
489
+
490
+ Args:
491
+ wrapped: The original 'embeddings' method to be wrapped.
492
+ instance: The instance of the class where the original method is defined.
493
+ args: Positional arguments for the 'embeddings' method.
494
+ kwargs: Keyword arguments for the 'embeddings' method.
495
+
496
+ Returns:
497
+ The response from the original 'embeddings' method.
498
+ """
499
+
500
+ with tracer.start_as_current_span(gen_ai_endpoint, kind= SpanKind.CLIENT) as span:
501
+ response = wrapped(*args, **kwargs)
502
+
503
+ try:
504
+ # Calculate cost of the operation
505
+ cost = 0
506
+ prompt_tokens = general_tokens(kwargs.get('prompt', ""))
507
+ # Set Span attributes
508
+ span.set_attribute(TELEMETRY_SDK_NAME, "openlit")
509
+ span.set_attribute(SemanticConvetion.GEN_AI_SYSTEM,
510
+ SemanticConvetion.GEN_AI_SYSTEM_OLLAMA)
511
+ span.set_attribute(SemanticConvetion.GEN_AI_TYPE,
512
+ SemanticConvetion.GEN_AI_TYPE_EMBEDDING)
513
+ span.set_attribute(SemanticConvetion.GEN_AI_ENDPOINT,
514
+ gen_ai_endpoint)
515
+ span.set_attribute(SemanticConvetion.GEN_AI_ENVIRONMENT,
516
+ environment)
517
+ span.set_attribute(SemanticConvetion.GEN_AI_APPLICATION_NAME,
518
+ application_name)
519
+ span.set_attribute(SemanticConvetion.GEN_AI_REQUEST_MODEL,
520
+ kwargs.get('model', "llama3"))
521
+ span.set_attribute(SemanticConvetion.GEN_AI_USAGE_PROMPT_TOKENS,
522
+ prompt_tokens)
523
+ span.set_attribute(SemanticConvetion.GEN_AI_USAGE_TOTAL_TOKENS,
524
+ prompt_tokens)
525
+ span.set_attribute(SemanticConvetion.GEN_AI_USAGE_COST,
526
+ cost)
527
+ if trace_content:
528
+ span.set_attribute(SemanticConvetion.GEN_AI_CONTENT_PROMPT,
529
+ kwargs.get('prompt', ""))
530
+
531
+ span.set_status(Status(StatusCode.OK))
532
+
533
+ if disable_metrics is False:
534
+ attributes = {
535
+ TELEMETRY_SDK_NAME:
536
+ "openlit",
537
+ SemanticConvetion.GEN_AI_APPLICATION_NAME:
538
+ application_name,
539
+ SemanticConvetion.GEN_AI_SYSTEM:
540
+ SemanticConvetion.GEN_AI_SYSTEM_OLLAMA,
541
+ SemanticConvetion.GEN_AI_ENVIRONMENT:
542
+ environment,
543
+ SemanticConvetion.GEN_AI_TYPE:
544
+ SemanticConvetion.GEN_AI_TYPE_EMBEDDING,
545
+ SemanticConvetion.GEN_AI_REQUEST_MODEL:
546
+ kwargs.get('model', "llama3")
547
+ }
548
+
549
+ metrics["genai_requests"].add(1, attributes)
550
+ metrics["genai_total_tokens"].add(prompt_tokens, attributes)
551
+ metrics["genai_prompt_tokens"].add(prompt_tokens, attributes)
552
+ metrics["genai_cost"].record(cost, attributes)
553
+
554
+ # Return original response
555
+ return response
556
+
557
+ except Exception as e:
558
+ handle_exception(span, e)
559
+ logger.error("Error in trace creation: %s", e)
560
+
561
+ # Return original response
562
+ return response
563
+
564
+ return wrapper
@@ -88,6 +88,7 @@ class SemanticConvetion:
88
88
  GEN_AI_SYSTEM_BEDROCK = "bedrock"
89
89
  GEN_AI_SYSTEM_VERTEXAI = "vertexai"
90
90
  GEN_AI_SYSTEM_GROQ = "groq"
91
+ GEN_AI_SYSTEM_OLLAMA = "ollama"
91
92
  GEN_AI_SYSTEM_LANGCHAIN = "langchain"
92
93
  GEN_AI_SYSTEM_LLAMAINDEX = "llama_index"
93
94
  GEN_AI_SYSTEM_HAYSTACK = "haystack"
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.1
2
2
  Name: openlit
3
- Version: 1.5.0
3
+ Version: 1.6.0
4
4
  Summary: OpenTelemetry-native Auto instrumentation library for monitoring LLM Applications, 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
@@ -50,6 +50,7 @@ This project adheres to the [Semantic Conventions](https://github.com/open-telem
50
50
 
51
51
  ### LLMs
52
52
  - [✅ OpenAI](https://docs.openlit.io/latest/integrations/openai)
53
+ - [✅ Ollama](https://docs.openlit.io/latest/integrations/ollama)
53
54
  - [✅ Anthropic](https://docs.openlit.io/latest/integrations/anthropic)
54
55
  - [✅ Cohere](https://docs.openlit.io/latest/integrations/cohere)
55
56
  - [✅ Mistral](https://docs.openlit.io/latest/integrations/mistral)
@@ -1,5 +1,5 @@
1
1
  openlit/__helpers.py,sha256=EEbLEUKuCiBp0WiieAvUnGcaU5D7grFgNVDCBgMKjQE,4651
2
- openlit/__init__.py,sha256=nm6JVVYnaslW5RQRvj1x0qnCQA_WBhAjHioY3w_IXlk,9647
2
+ openlit/__init__.py,sha256=6D83ebOY_LRaOtppUrgJdJfjosF3Ao4FtomEhH21pYY,9781
3
3
  openlit/instrumentation/anthropic/__init__.py,sha256=oaU53BOPyfUKbEzYvLr1DPymDluurSnwo4Hernf2XdU,1955
4
4
  openlit/instrumentation/anthropic/anthropic.py,sha256=CYBui5eEfWdSfFF0xtCQjh1xO-gCVJc_V9Hli0szVZE,16026
5
5
  openlit/instrumentation/anthropic/async_anthropic.py,sha256=NW84kTQ3BkUx1zZuMRps_J7zTYkmq5BxOrqSjqWInBs,16068
@@ -21,6 +21,9 @@ openlit/instrumentation/llamaindex/llamaindex.py,sha256=uiIigbwhonSbJWA7LpgOVI1R
21
21
  openlit/instrumentation/mistral/__init__.py,sha256=zJCIpFWRbsYrvooOJYuqwyuKeSOQLWbyXWCObL-Snks,3156
22
22
  openlit/instrumentation/mistral/async_mistral.py,sha256=PXpiLwkonTtAPVOUh9pXMSYeabwH0GFG_HRDWrEKhMM,21361
23
23
  openlit/instrumentation/mistral/mistral.py,sha256=nbAyMlPiuA9hihePkM_nnxAjahZSndT-B-qXRO5VIhk,21212
24
+ openlit/instrumentation/ollama/__init__.py,sha256=cOax8PiypDuo_FC4WvDCYBRo7lH5nV9xU92h7k-eZbg,3812
25
+ openlit/instrumentation/ollama/async_ollama.py,sha256=ESk1zZTj2hPmkWIH5F2owuoo0apleDSSx5VORlO3e3w,28991
26
+ openlit/instrumentation/ollama/ollama.py,sha256=PLGF9RB3TRNZ9GSGqeGVvKFBtgUK8Hc8xwvk-3NPeGI,28901
24
27
  openlit/instrumentation/openai/__init__.py,sha256=AZ2cPr3TMKkgGdMl_yXMeSi7bWhtmMqOW1iHdzHHGHA,16265
25
28
  openlit/instrumentation/openai/async_azure_openai.py,sha256=QE_5KHaCHAndkf7Y2Iq66mZUc0I1qtqIJ6iYPnwiuXA,46297
26
29
  openlit/instrumentation/openai/async_openai.py,sha256=qfJG_gIkSz3Gjau0zQ_G3tvkqkOd-md5LBK6wIjvH0U,45841
@@ -37,8 +40,8 @@ openlit/instrumentation/vertexai/async_vertexai.py,sha256=PMHYyLf1J4gZpC_-KZ_ZVx
37
40
  openlit/instrumentation/vertexai/vertexai.py,sha256=UvpNKBHPoV9idVMfGigZnmWuEQiyqSwZn0zK9-U7Lzw,52125
38
41
  openlit/otel/metrics.py,sha256=O7NoaDz0bY19mqpE4-0PcKwEe-B-iJFRgOCaanAuZAc,4291
39
42
  openlit/otel/tracing.py,sha256=vL1ifMbARPBpqK--yXYsCM6y5dSu5LFIKqkhZXtYmUc,3712
40
- openlit/semcov/__init__.py,sha256=0BHZuWE4strAmc-ilcVf6Nzoe0FEx0v9FStkccxs6mc,6168
41
- openlit-1.5.0.dist-info/LICENSE,sha256=xx0jnfkXJvxRnG63LTGOxlggYnIysveWIZ6H3PNdCrQ,11357
42
- openlit-1.5.0.dist-info/METADATA,sha256=Z0jWHca3OkoU_dcT2STaAvAFDf3xLbPtAXfOxGAK2m0,12146
43
- openlit-1.5.0.dist-info/WHEEL,sha256=sP946D7jFCHeNz5Iq4fL4Lu-PrWrFsgfLXbbkciIZwg,88
44
- openlit-1.5.0.dist-info/RECORD,,
43
+ openlit/semcov/__init__.py,sha256=3Whg8caSmGi-rF2PVkJohpCf5O3QjpgN7ai8r4XBIVI,6204
44
+ openlit-1.6.0.dist-info/LICENSE,sha256=xx0jnfkXJvxRnG63LTGOxlggYnIysveWIZ6H3PNdCrQ,11357
45
+ openlit-1.6.0.dist-info/METADATA,sha256=4qtHtjElIivkXWyJFXfUt-0_tTaidonqmJbT7Uvq8rc,12213
46
+ openlit-1.6.0.dist-info/WHEEL,sha256=sP946D7jFCHeNz5Iq4fL4Lu-PrWrFsgfLXbbkciIZwg,88
47
+ openlit-1.6.0.dist-info/RECORD,,