openlit 1.33.8__py3-none-any.whl → 1.33.10__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.
Files changed (92) hide show
  1. openlit/__helpers.py +88 -0
  2. openlit/__init__.py +4 -3
  3. openlit/instrumentation/ag2/ag2.py +5 -5
  4. openlit/instrumentation/ai21/__init__.py +4 -4
  5. openlit/instrumentation/ai21/ai21.py +370 -319
  6. openlit/instrumentation/ai21/async_ai21.py +371 -319
  7. openlit/instrumentation/anthropic/__init__.py +4 -4
  8. openlit/instrumentation/anthropic/anthropic.py +321 -189
  9. openlit/instrumentation/anthropic/async_anthropic.py +323 -190
  10. openlit/instrumentation/assemblyai/__init__.py +1 -1
  11. openlit/instrumentation/assemblyai/assemblyai.py +59 -43
  12. openlit/instrumentation/astra/astra.py +9 -9
  13. openlit/instrumentation/astra/async_astra.py +9 -9
  14. openlit/instrumentation/azure_ai_inference/__init__.py +4 -4
  15. openlit/instrumentation/azure_ai_inference/async_azure_ai_inference.py +406 -252
  16. openlit/instrumentation/azure_ai_inference/azure_ai_inference.py +406 -252
  17. openlit/instrumentation/bedrock/__init__.py +1 -1
  18. openlit/instrumentation/bedrock/bedrock.py +115 -58
  19. openlit/instrumentation/chroma/chroma.py +9 -9
  20. openlit/instrumentation/cohere/__init__.py +33 -10
  21. openlit/instrumentation/cohere/async_cohere.py +610 -0
  22. openlit/instrumentation/cohere/cohere.py +410 -219
  23. openlit/instrumentation/controlflow/controlflow.py +5 -5
  24. openlit/instrumentation/crawl4ai/async_crawl4ai.py +5 -5
  25. openlit/instrumentation/crawl4ai/crawl4ai.py +5 -5
  26. openlit/instrumentation/crewai/crewai.py +6 -4
  27. openlit/instrumentation/dynamiq/dynamiq.py +5 -5
  28. openlit/instrumentation/elevenlabs/async_elevenlabs.py +71 -46
  29. openlit/instrumentation/elevenlabs/elevenlabs.py +71 -51
  30. openlit/instrumentation/embedchain/embedchain.py +9 -9
  31. openlit/instrumentation/firecrawl/firecrawl.py +5 -5
  32. openlit/instrumentation/google_ai_studio/__init__.py +9 -9
  33. openlit/instrumentation/google_ai_studio/async_google_ai_studio.py +183 -219
  34. openlit/instrumentation/google_ai_studio/google_ai_studio.py +183 -220
  35. openlit/instrumentation/gpt4all/__init__.py +2 -2
  36. openlit/instrumentation/gpt4all/gpt4all.py +345 -220
  37. openlit/instrumentation/gpu/__init__.py +5 -5
  38. openlit/instrumentation/groq/__init__.py +2 -2
  39. openlit/instrumentation/groq/async_groq.py +356 -240
  40. openlit/instrumentation/groq/groq.py +356 -240
  41. openlit/instrumentation/haystack/haystack.py +5 -5
  42. openlit/instrumentation/julep/async_julep.py +5 -5
  43. openlit/instrumentation/julep/julep.py +5 -5
  44. openlit/instrumentation/langchain/__init__.py +13 -7
  45. openlit/instrumentation/langchain/async_langchain.py +384 -0
  46. openlit/instrumentation/langchain/langchain.py +105 -492
  47. openlit/instrumentation/letta/letta.py +11 -9
  48. openlit/instrumentation/litellm/__init__.py +4 -5
  49. openlit/instrumentation/litellm/async_litellm.py +318 -247
  50. openlit/instrumentation/litellm/litellm.py +314 -243
  51. openlit/instrumentation/llamaindex/llamaindex.py +5 -5
  52. openlit/instrumentation/mem0/mem0.py +5 -5
  53. openlit/instrumentation/milvus/milvus.py +9 -9
  54. openlit/instrumentation/mistral/__init__.py +6 -6
  55. openlit/instrumentation/mistral/async_mistral.py +423 -250
  56. openlit/instrumentation/mistral/mistral.py +420 -246
  57. openlit/instrumentation/multion/async_multion.py +6 -4
  58. openlit/instrumentation/multion/multion.py +6 -4
  59. openlit/instrumentation/ollama/__init__.py +8 -30
  60. openlit/instrumentation/ollama/async_ollama.py +385 -417
  61. openlit/instrumentation/ollama/ollama.py +384 -417
  62. openlit/instrumentation/openai/__init__.py +11 -230
  63. openlit/instrumentation/openai/async_openai.py +433 -410
  64. openlit/instrumentation/openai/openai.py +414 -394
  65. openlit/instrumentation/phidata/phidata.py +6 -4
  66. openlit/instrumentation/pinecone/pinecone.py +9 -9
  67. openlit/instrumentation/premai/__init__.py +2 -2
  68. openlit/instrumentation/premai/premai.py +262 -213
  69. openlit/instrumentation/qdrant/async_qdrant.py +9 -9
  70. openlit/instrumentation/qdrant/qdrant.py +9 -9
  71. openlit/instrumentation/reka/__init__.py +2 -2
  72. openlit/instrumentation/reka/async_reka.py +90 -52
  73. openlit/instrumentation/reka/reka.py +90 -52
  74. openlit/instrumentation/together/__init__.py +4 -4
  75. openlit/instrumentation/together/async_together.py +278 -236
  76. openlit/instrumentation/together/together.py +278 -236
  77. openlit/instrumentation/transformers/__init__.py +1 -1
  78. openlit/instrumentation/transformers/transformers.py +76 -45
  79. openlit/instrumentation/vertexai/__init__.py +14 -64
  80. openlit/instrumentation/vertexai/async_vertexai.py +330 -987
  81. openlit/instrumentation/vertexai/vertexai.py +330 -987
  82. openlit/instrumentation/vllm/__init__.py +1 -1
  83. openlit/instrumentation/vllm/vllm.py +66 -36
  84. openlit/otel/metrics.py +98 -7
  85. openlit/semcov/__init__.py +113 -80
  86. {openlit-1.33.8.dist-info → openlit-1.33.10.dist-info}/METADATA +1 -1
  87. openlit-1.33.10.dist-info/RECORD +122 -0
  88. {openlit-1.33.8.dist-info → openlit-1.33.10.dist-info}/WHEEL +1 -1
  89. openlit/instrumentation/openai/async_azure_openai.py +0 -900
  90. openlit/instrumentation/openai/azure_openai.py +0 -898
  91. openlit-1.33.8.dist-info/RECORD +0 -122
  92. {openlit-1.33.8.dist-info → openlit-1.33.10.dist-info}/LICENSE +0 -0
@@ -0,0 +1,610 @@
1
+ """
2
+ Module for monitoring Cohere API calls.
3
+ """
4
+
5
+ import logging
6
+ import time
7
+ from opentelemetry.trace import SpanKind, Status, StatusCode
8
+ from opentelemetry.sdk.resources import SERVICE_NAME, TELEMETRY_SDK_NAME, DEPLOYMENT_ENVIRONMENT
9
+ from openlit.__helpers import (
10
+ get_chat_model_cost,
11
+ get_embed_model_cost,
12
+ handle_exception,
13
+ response_as_dict,
14
+ calculate_ttft,
15
+ calculate_tbt,
16
+ create_metrics_attributes,
17
+ set_server_address_and_port
18
+ )
19
+ from openlit.semcov import SemanticConvetion
20
+
21
+ # Initialize logger for logging potential issues and operations
22
+ logger = logging.getLogger(__name__)
23
+
24
+ def async_embed(version, environment, application_name, tracer,
25
+ pricing_info, trace_content, metrics, disable_metrics):
26
+ """
27
+ Generates a telemetry wrapper for embeddings to collect metrics.
28
+
29
+ Args:
30
+ version: Version of the monitoring package.
31
+ environment: Deployment environment (e.g., production, staging).
32
+ application_name: Name of the application using the Cohere API.
33
+ tracer: OpenTelemetry tracer for creating spans.
34
+ pricing_info: Information used for calculating the cost of Cohere usage.
35
+ trace_content: Flag indicating whether to trace the actual content.
36
+
37
+ Returns:
38
+ A function that wraps the embeddings method to add telemetry.
39
+ """
40
+
41
+ async def wrapper(wrapped, instance, args, kwargs):
42
+ """
43
+ Wraps the 'embed' API call to add telemetry.
44
+
45
+ This collects metrics such as execution time, cost, and token usage, and handles errors
46
+ gracefully, adding details to the trace for observability.
47
+
48
+ Args:
49
+ wrapped: The original 'embed' method to be wrapped.
50
+ instance: The instance of the class where the original method is defined.
51
+ args: Positional arguments for the 'embed' method.
52
+ kwargs: Keyword arguments for the 'embed' method.
53
+
54
+ Returns:
55
+ The response from the original 'embed' method.
56
+ """
57
+
58
+ server_address, server_port = set_server_address_and_port(instance, "api.cohere.com", 443)
59
+ request_model = kwargs.get("model", "mbed-english-v3.0")
60
+
61
+ span_name = f"{SemanticConvetion.GEN_AI_OPERATION_TYPE_EMBEDDING} {request_model}"
62
+
63
+ with tracer.start_as_current_span(span_name, kind= SpanKind.CLIENT) as span:
64
+ start_time = time.time()
65
+ response = await wrapped(*args, **kwargs)
66
+ end_time = time.time()
67
+
68
+ response_dict = response_as_dict(response)
69
+ try:
70
+ input_tokens = response_dict.get('meta').get('billed_units').get('input_tokens')
71
+ # Calculate cost of the operation
72
+ cost = get_embed_model_cost(kwargs.get("model", "embed-english-v2.0"),
73
+ pricing_info, input_tokens)
74
+
75
+ # Set Span attributes (OTel Semconv)
76
+ span.set_attribute(TELEMETRY_SDK_NAME, "openlit")
77
+ span.set_attribute(SemanticConvetion.GEN_AI_OPERATION,
78
+ SemanticConvetion.GEN_AI_OPERATION_TYPE_EMBEDDING)
79
+ span.set_attribute(SemanticConvetion.GEN_AI_SYSTEM,
80
+ SemanticConvetion.GEN_AI_SYSTEM_COHERE)
81
+ span.set_attribute(SemanticConvetion.GEN_AI_REQUEST_MODEL,
82
+ request_model)
83
+ span.set_attribute(SemanticConvetion.GEN_AI_REQUEST_ENCODING_FORMATS,
84
+ kwargs.get('embedding_types', ['float']))
85
+ span.set_attribute(SemanticConvetion.GEN_AI_RESPONSE_MODEL,
86
+ request_model)
87
+ span.set_attribute(SemanticConvetion.SERVER_ADDRESS,
88
+ server_address)
89
+ span.set_attribute(SemanticConvetion.SERVER_PORT,
90
+ server_port)
91
+ span.set_attribute(SemanticConvetion.GEN_AI_USAGE_INPUT_TOKENS,
92
+ input_tokens)
93
+ span.set_attribute(SemanticConvetion.GEN_AI_OUTPUT_TYPE,
94
+ response_dict.get('response_type'))
95
+
96
+ # Set Span attributes (Extras)
97
+ span.set_attribute(DEPLOYMENT_ENVIRONMENT,
98
+ environment)
99
+ span.set_attribute(SERVICE_NAME,
100
+ application_name)
101
+ span.set_attribute(SemanticConvetion.GEN_AI_USAGE_TOTAL_TOKENS,
102
+ input_tokens)
103
+ span.set_attribute(SemanticConvetion.GEN_AI_USAGE_COST,
104
+ cost)
105
+ span.set_attribute(SemanticConvetion.GEN_AI_SDK_VERSION,
106
+ version)
107
+
108
+ if trace_content:
109
+ span.add_event(
110
+ name=SemanticConvetion.GEN_AI_CONTENT_PROMPT_EVENT,
111
+ attributes={
112
+ SemanticConvetion.GEN_AI_CONTENT_PROMPT: str(kwargs.get("texts", "")),
113
+ },
114
+ )
115
+
116
+ span.set_status(Status(StatusCode.OK))
117
+
118
+ if disable_metrics is False:
119
+ attributes = create_metrics_attributes(
120
+ service_name=application_name,
121
+ deployment_environment=environment,
122
+ operation=SemanticConvetion.GEN_AI_OPERATION_TYPE_EMBEDDING,
123
+ system=SemanticConvetion.GEN_AI_SYSTEM_COHERE,
124
+ request_model=request_model,
125
+ server_address=server_address,
126
+ server_port=server_port,
127
+ response_model=request_model,
128
+ )
129
+ metrics["genai_client_usage_tokens"].record(
130
+ input_tokens, attributes
131
+ )
132
+ metrics["genai_client_operation_duration"].record(
133
+ end_time - start_time, attributes
134
+ )
135
+ metrics["genai_requests"].add(1, attributes)
136
+ metrics["genai_prompt_tokens"].add(input_tokens, attributes)
137
+ metrics["genai_cost"].record(cost, attributes)
138
+
139
+ # Return original response
140
+ return response
141
+
142
+ except Exception as e:
143
+ handle_exception(span, e)
144
+ logger.error("Error in trace creation: %s", e)
145
+
146
+ # Return original response
147
+ return response
148
+
149
+ return wrapper
150
+
151
+ def async_chat(version, environment, application_name, tracer,
152
+ pricing_info, trace_content, metrics, disable_metrics):
153
+ """
154
+ Generates a telemetry wrapper for chat to collect metrics.
155
+
156
+ Args:
157
+ version: Version of the monitoring package.
158
+ environment: Deployment environment (e.g., production, staging).
159
+ application_name: Name of the application using the Cohere API.
160
+ tracer: OpenTelemetry tracer for creating spans.
161
+ pricing_info: Information used for calculating the cost of Cohere usage.
162
+ trace_content: Flag indicating whether to trace the actual content.
163
+
164
+ Returns:
165
+ A function that wraps the chat method to add telemetry.
166
+ """
167
+
168
+ async def wrapper(wrapped, instance, args, kwargs):
169
+ """
170
+ Wraps the 'chat' API call to add telemetry.
171
+
172
+ This collects metrics such as execution time, cost, and token usage, and handles errors
173
+ gracefully, adding details to the trace for observability.
174
+
175
+ Args:
176
+ wrapped: The original 'chat' method to be wrapped.
177
+ instance: The instance of the class where the original method is defined.
178
+ args: Positional arguments for the 'chat' method.
179
+ kwargs: Keyword arguments for the 'chat' method.
180
+
181
+ Returns:
182
+ The response from the original 'chat' method.
183
+ """
184
+
185
+ server_address, server_port = set_server_address_and_port(instance, "api.cohere.com", 443)
186
+ request_model = kwargs.get("model", "command-r-plus-08-2024")
187
+
188
+ span_name = f"{SemanticConvetion.GEN_AI_OPERATION_TYPE_CHAT} {request_model}"
189
+
190
+ with tracer.start_as_current_span(span_name, kind=SpanKind.CLIENT) as span:
191
+ start_time = time.time()
192
+ response = await wrapped(*args, **kwargs)
193
+ end_time = time.time()
194
+
195
+ response_dict = response_as_dict(response)
196
+
197
+ try:
198
+ # Format 'messages' into a single string
199
+ message_prompt = kwargs.get("messages", "")
200
+ formatted_messages = []
201
+ for message in message_prompt:
202
+ role = message["role"]
203
+ content = message["content"]
204
+
205
+ if isinstance(content, list):
206
+ content_str = ", ".join(
207
+ f'{item["type"]}: {item["text"] if "text" in item else item["image_url"]}'
208
+ if "type" in item else f'text: {item["text"]}'
209
+ for item in content
210
+ )
211
+ formatted_messages.append(f"{role}: {content_str}")
212
+ else:
213
+ formatted_messages.append(f"{role}: {content}")
214
+ prompt = "\n".join(formatted_messages)
215
+
216
+ input_tokens = response_dict.get('usage').get('billed_units').get('input_tokens')
217
+ output_tokens = response_dict.get('usage').get('billed_units').get('output_tokens')
218
+
219
+ # Calculate cost of the operation
220
+ cost = get_chat_model_cost(request_model, pricing_info,
221
+ input_tokens, output_tokens)
222
+
223
+ llm_response = response_dict.get('message').get('content')[0].get('text')
224
+
225
+ # Set base span attribues (OTel Semconv)
226
+ span.set_attribute(TELEMETRY_SDK_NAME, "openlit")
227
+ span.set_attribute(SemanticConvetion.GEN_AI_OPERATION,
228
+ SemanticConvetion.GEN_AI_OPERATION_TYPE_CHAT)
229
+ span.set_attribute(SemanticConvetion.GEN_AI_SYSTEM,
230
+ SemanticConvetion.GEN_AI_SYSTEM_COHERE)
231
+ span.set_attribute(SemanticConvetion.GEN_AI_REQUEST_MODEL,
232
+ request_model)
233
+ span.set_attribute(SemanticConvetion.GEN_AI_REQUEST_SEED,
234
+ kwargs.get("seed", ""))
235
+ span.set_attribute(SemanticConvetion.SERVER_PORT,
236
+ server_port)
237
+ span.set_attribute(SemanticConvetion.GEN_AI_REQUEST_FREQUENCY_PENALTY,
238
+ kwargs.get("frequency_penalty", 0.0))
239
+ span.set_attribute(SemanticConvetion.GEN_AI_REQUEST_MAX_TOKENS,
240
+ kwargs.get("max_tokens", -1))
241
+ span.set_attribute(SemanticConvetion.GEN_AI_REQUEST_PRESENCE_PENALTY,
242
+ kwargs.get("presence_penalty", 0.0))
243
+ span.set_attribute(SemanticConvetion.GEN_AI_REQUEST_STOP_SEQUENCES,
244
+ kwargs.get("stop_sequences", []))
245
+ span.set_attribute(SemanticConvetion.GEN_AI_REQUEST_TEMPERATURE,
246
+ kwargs.get("temperature", 0.3))
247
+ span.set_attribute(SemanticConvetion.GEN_AI_REQUEST_TOP_K,
248
+ kwargs.get("k", 1.0))
249
+ span.set_attribute(SemanticConvetion.GEN_AI_REQUEST_TOP_P,
250
+ kwargs.get("p", 1.0))
251
+ span.set_attribute(SemanticConvetion.GEN_AI_RESPONSE_ID,
252
+ response_dict.get("id"))
253
+ span.set_attribute(SemanticConvetion.GEN_AI_RESPONSE_MODEL,
254
+ request_model)
255
+ span.set_attribute(SemanticConvetion.GEN_AI_USAGE_INPUT_TOKENS,
256
+ input_tokens)
257
+ span.set_attribute(SemanticConvetion.GEN_AI_USAGE_OUTPUT_TOKENS,
258
+ output_tokens)
259
+ span.set_attribute(SemanticConvetion.SERVER_ADDRESS,
260
+ server_address)
261
+ if isinstance(llm_response, str):
262
+ span.set_attribute(SemanticConvetion.GEN_AI_OUTPUT_TYPE,
263
+ "text")
264
+ else:
265
+ span.set_attribute(SemanticConvetion.GEN_AI_OUTPUT_TYPE,
266
+ "json")
267
+
268
+ # Set base span attribues (Extras)
269
+ span.set_attribute(DEPLOYMENT_ENVIRONMENT,
270
+ environment)
271
+ span.set_attribute(SERVICE_NAME,
272
+ application_name)
273
+ span.set_attribute(SemanticConvetion.GEN_AI_REQUEST_IS_STREAM,
274
+ False)
275
+ span.set_attribute(SemanticConvetion.GEN_AI_USAGE_TOTAL_TOKENS,
276
+ input_tokens + output_tokens)
277
+ span.set_attribute(SemanticConvetion.GEN_AI_USAGE_COST,
278
+ cost)
279
+ span.set_attribute(SemanticConvetion.GEN_AI_SERVER_TTFT,
280
+ end_time - start_time)
281
+ span.set_attribute(SemanticConvetion.GEN_AI_SDK_VERSION,
282
+ version)
283
+
284
+ if trace_content:
285
+ span.add_event(
286
+ name=SemanticConvetion.GEN_AI_CONTENT_PROMPT_EVENT,
287
+ attributes={
288
+ SemanticConvetion.GEN_AI_CONTENT_PROMPT: prompt,
289
+ },
290
+ )
291
+ span.add_event(
292
+ name=SemanticConvetion.GEN_AI_CONTENT_COMPLETION_EVENT,
293
+ attributes={
294
+ SemanticConvetion.GEN_AI_CONTENT_COMPLETION: llm_response,
295
+ },
296
+ )
297
+
298
+ span.set_status(Status(StatusCode.OK))
299
+
300
+ if disable_metrics is False:
301
+ attributes = create_metrics_attributes(
302
+ service_name=application_name,
303
+ deployment_environment=environment,
304
+ operation=SemanticConvetion.GEN_AI_OPERATION_TYPE_CHAT,
305
+ system=SemanticConvetion.GEN_AI_SYSTEM_COHERE,
306
+ request_model=request_model,
307
+ server_address=server_address,
308
+ server_port=server_port,
309
+ response_model=request_model,
310
+ )
311
+
312
+ metrics["genai_client_usage_tokens"].record(
313
+ input_tokens + output_tokens, attributes
314
+ )
315
+ metrics["genai_client_operation_duration"].record(
316
+ end_time - start_time, attributes
317
+ )
318
+ metrics["genai_server_ttft"].record(
319
+ end_time - start_time, attributes
320
+ )
321
+ metrics["genai_requests"].add(1, attributes)
322
+ metrics["genai_completion_tokens"].add(output_tokens, attributes)
323
+ metrics["genai_prompt_tokens"].add(input_tokens, attributes)
324
+ metrics["genai_cost"].record(cost, attributes)
325
+
326
+ # Return original response
327
+ return response
328
+
329
+ except Exception as e:
330
+ handle_exception(span, e)
331
+ logger.error("Error in trace creation: %s", e)
332
+
333
+ # Return original response
334
+ return response
335
+
336
+ return wrapper
337
+
338
+ def async_chat_stream(version, environment, application_name,
339
+ tracer, pricing_info, trace_content, metrics, disable_metrics):
340
+ """
341
+ Generates a telemetry wrapper for chat_stream to collect metrics.
342
+
343
+ Args:
344
+ version: Version of the monitoring package.
345
+ environment: Deployment environment (e.g., production, staging).
346
+ application_name: Name of the application using the Cohere API.
347
+ tracer: OpenTelemetry tracer for creating spans.
348
+ pricing_info: Information used for calculating the cost of Cohere usage.
349
+ trace_content: Flag indicating whether to trace the actual content.
350
+
351
+ Returns:
352
+ A function that wraps the chat method to add telemetry.
353
+ """
354
+
355
+ async def wrapper(wrapped, instance, args, kwargs):
356
+ """
357
+ Wraps the 'chat_stream' API call to add telemetry.
358
+
359
+ This collects metrics such as execution time, cost, and token usage, and handles errors
360
+ gracefully, adding details to the trace for observability.
361
+
362
+ Args:
363
+ wrapped: The original 'chat_stream' method to be wrapped.
364
+ instance: The instance of the class where the original method is defined.
365
+ args: Positional arguments for the 'chat_stream' method.
366
+ kwargs: Keyword arguments for the 'chat_stream' method.
367
+
368
+ Returns:
369
+ The response from the original 'chat_stream' method.
370
+ """
371
+
372
+ class TracedAsyncStream:
373
+ """
374
+ Wrapper for streaming responses to collect metrics and trace data.
375
+ Wraps the response to collect message IDs and aggregated response.
376
+
377
+ This class implements the '__aiter__' and '__anext__' methods that
378
+ handle asynchronous streaming responses.
379
+
380
+ This class also implements '__aenter__' and '__aexit__' methods that
381
+ handle asynchronous context management protocol.
382
+ """
383
+ def __init__(
384
+ self,
385
+ wrapped,
386
+ span,
387
+ kwargs,
388
+ server_address,
389
+ server_port,
390
+ **args,
391
+ ):
392
+ self.__wrapped__ = wrapped
393
+ self._span = span
394
+ # Placeholder for aggregating streaming response
395
+ self._llmresponse = ""
396
+ self._response_id = ""
397
+ self._finish_reason = ""
398
+ self._input_tokens = ""
399
+ self._output_tokens = ""
400
+
401
+ self._args = args
402
+ self._kwargs = kwargs
403
+ self._start_time = time.time()
404
+ self._end_time = None
405
+ self._timestamps = []
406
+ self._ttft = 0
407
+ self._tbt = 0
408
+ self._server_address = server_address
409
+ self._server_port = server_port
410
+
411
+ async def __aenter__(self):
412
+ await self.__wrapped__.__aenter__()
413
+ return self
414
+
415
+ async def __aexit__(self, exc_type, exc_value, traceback):
416
+ await self.__wrapped__.__aexit__(exc_type, exc_value, traceback)
417
+
418
+ def __aiter__(self):
419
+ return self
420
+
421
+ async def __getattr__(self, name):
422
+ """Delegate attribute access to the wrapped object."""
423
+ return getattr(await self.__wrapped__, name)
424
+
425
+ async def __anext__(self):
426
+ try:
427
+ chunk = await self.__wrapped__.__anext__()
428
+ end_time = time.time()
429
+ # Record the timestamp for the current chunk
430
+ self._timestamps.append(end_time)
431
+
432
+ if len(self._timestamps) == 1:
433
+ # Calculate time to first chunk
434
+ self._ttft = calculate_ttft(self._timestamps, self._start_time)
435
+
436
+ chunked = response_as_dict(chunk)
437
+
438
+ if chunked.get('type') == 'message-start':
439
+ self._response_id = chunked.get('id')
440
+
441
+ if chunked.get('type') == 'content-delta':
442
+ content = chunked.get('delta').get('message').get('text')
443
+ if content:
444
+ self._llmresponse += content
445
+
446
+ if chunked.get('type') == 'message-end':
447
+ self._finish_reason = chunked.get('delta').get('finish_reason')
448
+ self._input_tokens = chunked.get('delta').get('usage').get('billed_units').get('input_tokens')
449
+ self._output_tokens = chunked.get('delta').get('usage').get('billed_units').get('output_tokens')
450
+
451
+ return chunk
452
+ except StopAsyncIteration:
453
+ # Handling exception ensure observability without disrupting operation
454
+ try:
455
+ self._end_time = time.time()
456
+ if len(self._timestamps) > 1:
457
+ self._tbt = calculate_tbt(self._timestamps)
458
+
459
+ # Format 'messages' into a single string
460
+ message_prompt = self._kwargs.get("messages", "")
461
+ formatted_messages = []
462
+ for message in message_prompt:
463
+ role = message["role"]
464
+ content = message["content"]
465
+
466
+ if isinstance(content, list):
467
+ content_str_list = []
468
+ for item in content:
469
+ if item["type"] == "text":
470
+ content_str_list.append(f'text: {item["text"]}')
471
+ elif (item["type"] == "image_url" and
472
+ not item["image_url"]["url"].startswith("data:")):
473
+ content_str_list.append(f'image_url: {item["image_url"]["url"]}')
474
+ content_str = ", ".join(content_str_list)
475
+ formatted_messages.append(f"{role}: {content_str}")
476
+ else:
477
+ formatted_messages.append(f"{role}: {content}")
478
+ prompt = "\n".join(formatted_messages)
479
+
480
+ request_model = self._kwargs.get("model", "command-r-plus")
481
+
482
+ # Calculate cost of the operation
483
+ cost = get_chat_model_cost(request_model,
484
+ pricing_info, self._input_tokens,
485
+ self._output_tokens)
486
+
487
+ # Set Span attributes (OTel Semconv)
488
+ self._span.set_attribute(TELEMETRY_SDK_NAME, "openlit")
489
+ self._span.set_attribute(SemanticConvetion.GEN_AI_OPERATION,
490
+ SemanticConvetion.GEN_AI_OPERATION_TYPE_CHAT)
491
+ self._span.set_attribute(SemanticConvetion.GEN_AI_SYSTEM,
492
+ SemanticConvetion.GEN_AI_SYSTEM_COHERE)
493
+ self._span.set_attribute(SemanticConvetion.GEN_AI_REQUEST_MODEL,
494
+ request_model)
495
+ self._span.set_attribute(SemanticConvetion.GEN_AI_REQUEST_SEED,
496
+ self._kwargs.get("seed", ""))
497
+ self._span.set_attribute(SemanticConvetion.SERVER_PORT,
498
+ self._server_port)
499
+ self._span.set_attribute(SemanticConvetion.GEN_AI_REQUEST_FREQUENCY_PENALTY,
500
+ self._kwargs.get("frequency_penalty", 0.0))
501
+ self._span.set_attribute(SemanticConvetion.GEN_AI_REQUEST_MAX_TOKENS,
502
+ self._kwargs.get("max_tokens", -1))
503
+ self._span.set_attribute(SemanticConvetion.GEN_AI_REQUEST_PRESENCE_PENALTY,
504
+ self._kwargs.get("presence_penalty", 0.0))
505
+ self._span.set_attribute(SemanticConvetion.GEN_AI_REQUEST_STOP_SEQUENCES,
506
+ self._kwargs.get("stop_sequences", []))
507
+ self._span.set_attribute(SemanticConvetion.GEN_AI_REQUEST_TEMPERATURE,
508
+ self._kwargs.get("temperature", 0.3))
509
+ self._span.set_attribute(SemanticConvetion.GEN_AI_REQUEST_TOP_K,
510
+ self._kwargs.get("k", 1.0))
511
+ self._span.set_attribute(SemanticConvetion.GEN_AI_REQUEST_TOP_P,
512
+ self._kwargs.get("p", 1.0))
513
+ self._span.set_attribute(SemanticConvetion.GEN_AI_RESPONSE_FINISH_REASON,
514
+ [self._finish_reason])
515
+ self._span.set_attribute(SemanticConvetion.GEN_AI_RESPONSE_ID,
516
+ self._response_id)
517
+ self._span.set_attribute(SemanticConvetion.GEN_AI_RESPONSE_MODEL,
518
+ request_model)
519
+ self._span.set_attribute(SemanticConvetion.GEN_AI_USAGE_INPUT_TOKENS,
520
+ self._input_tokens)
521
+ self._span.set_attribute(SemanticConvetion.GEN_AI_USAGE_OUTPUT_TOKENS,
522
+ self._output_tokens)
523
+ self._span.set_attribute(SemanticConvetion.SERVER_ADDRESS,
524
+ self._server_address)
525
+
526
+ if isinstance(self._llmresponse, str):
527
+ self._span.set_attribute(SemanticConvetion.GEN_AI_OUTPUT_TYPE,
528
+ "text")
529
+ else:
530
+ self._span.set_attribute(SemanticConvetion.GEN_AI_OUTPUT_TYPE,
531
+ "json")
532
+
533
+ # Set Span attributes (Extra)
534
+ self._span.set_attribute(DEPLOYMENT_ENVIRONMENT,
535
+ environment)
536
+ self._span.set_attribute(SERVICE_NAME,
537
+ application_name)
538
+ self._span.set_attribute(SemanticConvetion.GEN_AI_REQUEST_IS_STREAM,
539
+ True)
540
+ self._span.set_attribute(SemanticConvetion.GEN_AI_USAGE_TOTAL_TOKENS,
541
+ self._input_tokens + self._output_tokens)
542
+ self._span.set_attribute(SemanticConvetion.GEN_AI_USAGE_COST,
543
+ cost)
544
+ self._span.set_attribute(SemanticConvetion.GEN_AI_SERVER_TBT,
545
+ self._tbt)
546
+ self._span.set_attribute(SemanticConvetion.GEN_AI_SERVER_TTFT,
547
+ self._ttft)
548
+ self._span.set_attribute(SemanticConvetion.GEN_AI_SDK_VERSION,
549
+ version)
550
+ if trace_content:
551
+ self._span.add_event(
552
+ name=SemanticConvetion.GEN_AI_CONTENT_PROMPT_EVENT,
553
+ attributes={
554
+ SemanticConvetion.GEN_AI_CONTENT_PROMPT: prompt,
555
+ },
556
+ )
557
+ self._span.add_event(
558
+ name=SemanticConvetion.GEN_AI_CONTENT_COMPLETION_EVENT,
559
+ attributes={
560
+ SemanticConvetion.GEN_AI_CONTENT_COMPLETION: self._llmresponse,
561
+ },
562
+ )
563
+ self._span.set_status(Status(StatusCode.OK))
564
+
565
+ if disable_metrics is False:
566
+ attributes = create_metrics_attributes(
567
+ service_name=application_name,
568
+ deployment_environment=environment,
569
+ operation=SemanticConvetion.GEN_AI_OPERATION_TYPE_CHAT,
570
+ system=SemanticConvetion.GEN_AI_SYSTEM_COHERE,
571
+ request_model=request_model,
572
+ server_address=self._server_address,
573
+ server_port=self._server_port,
574
+ response_model=request_model,
575
+ )
576
+
577
+ metrics["genai_client_usage_tokens"].record(
578
+ self._input_tokens + self._output_tokens, attributes
579
+ )
580
+ metrics["genai_client_operation_duration"].record(
581
+ self._end_time - self._start_time, attributes
582
+ )
583
+ metrics["genai_server_tbt"].record(
584
+ self._tbt, attributes
585
+ )
586
+ metrics["genai_server_ttft"].record(
587
+ self._ttft, attributes
588
+ )
589
+ metrics["genai_requests"].add(1, attributes)
590
+ metrics["genai_completion_tokens"].add(self._output_tokens, attributes)
591
+ metrics["genai_prompt_tokens"].add(self._input_tokens, attributes)
592
+ metrics["genai_cost"].record(cost, attributes)
593
+
594
+ except Exception as e:
595
+ handle_exception(self._span, e)
596
+ logger.error("Error in trace creation: %s", e)
597
+ finally:
598
+ self._span.end()
599
+ raise
600
+
601
+ server_address, server_port = set_server_address_and_port(instance, "api.cohere.com", 443)
602
+ request_model = kwargs.get("model", "command-r-plus")
603
+
604
+ span_name = f"{SemanticConvetion.GEN_AI_OPERATION_TYPE_CHAT} {request_model}"
605
+
606
+ awaited_wrapped = await wrapped(*args, **kwargs)
607
+ span = tracer.start_span(span_name, kind=SpanKind.CLIENT)
608
+ return TracedAsyncStream(awaited_wrapped, span, kwargs, server_address, server_port)
609
+
610
+ return wrapper