openlit 1.33.8__py3-none-any.whl → 1.33.9__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 +83 -0
- openlit/__init__.py +1 -1
- openlit/instrumentation/ag2/ag2.py +2 -2
- openlit/instrumentation/ai21/__init__.py +4 -4
- openlit/instrumentation/ai21/ai21.py +370 -319
- openlit/instrumentation/ai21/async_ai21.py +371 -319
- openlit/instrumentation/anthropic/__init__.py +4 -4
- openlit/instrumentation/anthropic/anthropic.py +321 -189
- openlit/instrumentation/anthropic/async_anthropic.py +323 -190
- openlit/instrumentation/assemblyai/__init__.py +1 -1
- openlit/instrumentation/assemblyai/assemblyai.py +59 -43
- openlit/instrumentation/astra/astra.py +4 -4
- openlit/instrumentation/astra/async_astra.py +4 -4
- openlit/instrumentation/azure_ai_inference/__init__.py +4 -4
- openlit/instrumentation/azure_ai_inference/async_azure_ai_inference.py +406 -252
- openlit/instrumentation/azure_ai_inference/azure_ai_inference.py +406 -252
- openlit/instrumentation/bedrock/__init__.py +1 -1
- openlit/instrumentation/bedrock/bedrock.py +115 -58
- openlit/instrumentation/chroma/chroma.py +4 -4
- openlit/instrumentation/cohere/__init__.py +33 -10
- openlit/instrumentation/cohere/async_cohere.py +610 -0
- openlit/instrumentation/cohere/cohere.py +410 -219
- openlit/instrumentation/controlflow/controlflow.py +2 -2
- openlit/instrumentation/crawl4ai/async_crawl4ai.py +2 -2
- openlit/instrumentation/crawl4ai/crawl4ai.py +2 -2
- openlit/instrumentation/crewai/crewai.py +2 -2
- openlit/instrumentation/dynamiq/dynamiq.py +2 -2
- openlit/instrumentation/elevenlabs/async_elevenlabs.py +73 -47
- openlit/instrumentation/elevenlabs/elevenlabs.py +73 -52
- openlit/instrumentation/embedchain/embedchain.py +4 -4
- openlit/instrumentation/firecrawl/firecrawl.py +2 -2
- openlit/instrumentation/google_ai_studio/__init__.py +9 -9
- openlit/instrumentation/google_ai_studio/async_google_ai_studio.py +183 -219
- openlit/instrumentation/google_ai_studio/google_ai_studio.py +183 -220
- openlit/instrumentation/gpt4all/gpt4all.py +17 -17
- openlit/instrumentation/groq/async_groq.py +14 -14
- openlit/instrumentation/groq/groq.py +14 -14
- openlit/instrumentation/haystack/haystack.py +2 -2
- openlit/instrumentation/julep/async_julep.py +2 -2
- openlit/instrumentation/julep/julep.py +2 -2
- openlit/instrumentation/langchain/langchain.py +36 -31
- openlit/instrumentation/letta/letta.py +6 -6
- openlit/instrumentation/litellm/async_litellm.py +20 -20
- openlit/instrumentation/litellm/litellm.py +20 -20
- openlit/instrumentation/llamaindex/llamaindex.py +2 -2
- openlit/instrumentation/mem0/mem0.py +2 -2
- openlit/instrumentation/milvus/milvus.py +4 -4
- openlit/instrumentation/mistral/async_mistral.py +18 -18
- openlit/instrumentation/mistral/mistral.py +18 -18
- openlit/instrumentation/multion/async_multion.py +2 -2
- openlit/instrumentation/multion/multion.py +2 -2
- openlit/instrumentation/ollama/async_ollama.py +29 -29
- openlit/instrumentation/ollama/ollama.py +29 -29
- openlit/instrumentation/openai/__init__.py +11 -230
- openlit/instrumentation/openai/async_openai.py +434 -409
- openlit/instrumentation/openai/openai.py +415 -393
- openlit/instrumentation/phidata/phidata.py +2 -2
- openlit/instrumentation/pinecone/pinecone.py +4 -4
- openlit/instrumentation/premai/premai.py +20 -20
- openlit/instrumentation/qdrant/async_qdrant.py +4 -4
- openlit/instrumentation/qdrant/qdrant.py +4 -4
- openlit/instrumentation/reka/async_reka.py +6 -6
- openlit/instrumentation/reka/reka.py +6 -6
- openlit/instrumentation/together/async_together.py +18 -18
- openlit/instrumentation/together/together.py +18 -18
- openlit/instrumentation/transformers/transformers.py +6 -6
- openlit/instrumentation/vertexai/async_vertexai.py +53 -53
- openlit/instrumentation/vertexai/vertexai.py +53 -53
- openlit/instrumentation/vllm/vllm.py +6 -6
- openlit/otel/metrics.py +98 -7
- openlit/semcov/__init__.py +113 -80
- {openlit-1.33.8.dist-info → openlit-1.33.9.dist-info}/METADATA +1 -1
- openlit-1.33.9.dist-info/RECORD +121 -0
- {openlit-1.33.8.dist-info → openlit-1.33.9.dist-info}/WHEEL +1 -1
- openlit/instrumentation/openai/async_azure_openai.py +0 -900
- openlit/instrumentation/openai/azure_openai.py +0 -898
- openlit-1.33.8.dist-info/RECORD +0 -122
- {openlit-1.33.8.dist-info → openlit-1.33.9.dist-info}/LICENSE +0 -0
@@ -1,35 +1,267 @@
|
|
1
|
-
# pylint: disable=duplicate-code, broad-exception-caught, too-many-statements, unused-argument, possibly-used-before-assignment
|
2
1
|
"""
|
3
2
|
Module for monitoring Anthropic API calls.
|
4
3
|
"""
|
5
4
|
|
6
5
|
import logging
|
6
|
+
import time
|
7
7
|
from opentelemetry.trace import SpanKind, Status, StatusCode
|
8
|
-
from opentelemetry.sdk.resources import TELEMETRY_SDK_NAME
|
9
|
-
from openlit.__helpers import
|
8
|
+
from opentelemetry.sdk.resources import SERVICE_NAME, TELEMETRY_SDK_NAME, DEPLOYMENT_ENVIRONMENT
|
9
|
+
from openlit.__helpers import (
|
10
|
+
get_chat_model_cost,
|
11
|
+
handle_exception,
|
12
|
+
response_as_dict,
|
13
|
+
calculate_ttft,
|
14
|
+
calculate_tbt,
|
15
|
+
create_metrics_attributes,
|
16
|
+
set_server_address_and_port
|
17
|
+
)
|
10
18
|
from openlit.semcov import SemanticConvetion
|
11
19
|
|
12
20
|
# Initialize logger for logging potential issues and operations
|
13
21
|
logger = logging.getLogger(__name__)
|
14
22
|
|
15
|
-
def async_messages(
|
16
|
-
|
23
|
+
def async_messages(version, environment, application_name, tracer,
|
24
|
+
pricing_info, trace_content, metrics, disable_metrics):
|
17
25
|
"""
|
18
26
|
Generates a telemetry wrapper for messages to collect metrics.
|
19
27
|
|
20
28
|
Args:
|
21
|
-
gen_ai_endpoint: Endpoint identifier for logging and tracing.
|
22
29
|
version: Version of the monitoring package.
|
23
30
|
environment: Deployment environment (e.g., production, staging).
|
24
|
-
application_name: Name of the application using the
|
31
|
+
application_name: Name of the application using the Anthropic API.
|
25
32
|
tracer: OpenTelemetry tracer for creating spans.
|
26
|
-
pricing_info: Information used for calculating the cost of
|
33
|
+
pricing_info: Information used for calculating the cost of Anthropic usage.
|
27
34
|
trace_content: Flag indicating whether to trace the actual content.
|
28
35
|
|
29
36
|
Returns:
|
30
37
|
A function that wraps the chat method to add telemetry.
|
31
38
|
"""
|
32
39
|
|
40
|
+
class TracedASyncStream:
|
41
|
+
"""
|
42
|
+
Wrapper for streaming responses to collect metrics and trace data.
|
43
|
+
Wraps the 'anthropic.AsyncStream' response to collect message IDs and aggregated response.
|
44
|
+
|
45
|
+
This class implements the '__aiter__' and '__anext__' methods that
|
46
|
+
handle asynchronous streaming responses.
|
47
|
+
|
48
|
+
This class also implements '__aenter__' and '__aexit__' methods that
|
49
|
+
handle asynchronous context management protocol.
|
50
|
+
"""
|
51
|
+
def __init__(
|
52
|
+
self,
|
53
|
+
wrapped,
|
54
|
+
span,
|
55
|
+
kwargs,
|
56
|
+
server_address,
|
57
|
+
server_port,
|
58
|
+
**args,
|
59
|
+
):
|
60
|
+
self.__wrapped__ = wrapped
|
61
|
+
self._span = span
|
62
|
+
# Placeholder for aggregating streaming response
|
63
|
+
self._llmresponse = ""
|
64
|
+
self._response_id = ""
|
65
|
+
self._response_model = ""
|
66
|
+
self._finish_reason = ""
|
67
|
+
self._input_tokens = ""
|
68
|
+
self._output_tokens = ""
|
69
|
+
|
70
|
+
self._args = args
|
71
|
+
self._kwargs = kwargs
|
72
|
+
self._start_time = time.time()
|
73
|
+
self._end_time = None
|
74
|
+
self._timestamps = []
|
75
|
+
self._ttft = 0
|
76
|
+
self._tbt = 0
|
77
|
+
self._server_address = server_address
|
78
|
+
self._server_port = server_port
|
79
|
+
|
80
|
+
async def __aenter__(self):
|
81
|
+
await self.__wrapped__.__aenter__()
|
82
|
+
return self
|
83
|
+
|
84
|
+
async def __aexit__(self, exc_type, exc_value, traceback):
|
85
|
+
await self.__wrapped__.__aexit__(exc_type, exc_value, traceback)
|
86
|
+
|
87
|
+
def __aiter__(self):
|
88
|
+
return self
|
89
|
+
|
90
|
+
async def __getattr__(self, name):
|
91
|
+
"""Delegate attribute access to the wrapped object."""
|
92
|
+
return getattr(await self.__wrapped__, name)
|
93
|
+
|
94
|
+
async def __anext__(self):
|
95
|
+
try:
|
96
|
+
chunk = await self.__wrapped__.__anext__()
|
97
|
+
end_time = time.time()
|
98
|
+
# Record the timestamp for the current chunk
|
99
|
+
self._timestamps.append(end_time)
|
100
|
+
|
101
|
+
if len(self._timestamps) == 1:
|
102
|
+
# Calculate time to first chunk
|
103
|
+
self._ttft = calculate_ttft(self._timestamps, self._start_time)
|
104
|
+
|
105
|
+
chunked = response_as_dict(chunk)
|
106
|
+
|
107
|
+
# Collect message IDs and input token from events
|
108
|
+
if chunked.get('type') == "message_start":
|
109
|
+
self._response_id = chunked.get('message').get('id')
|
110
|
+
self._input_tokens = chunked.get('message').get('usage').get('input_tokens')
|
111
|
+
self._response_model = chunked.get('message').get('model')
|
112
|
+
# Collect message IDs and aggregated response from events
|
113
|
+
if chunked.get('type') == "content_block_delta":
|
114
|
+
content = chunked.get('delta').get('text')
|
115
|
+
if content:
|
116
|
+
self._llmresponse += content
|
117
|
+
# Collect output tokens and stop reason from events
|
118
|
+
if chunked.get('type') == "message_delta":
|
119
|
+
self._output_tokens = chunked.get('usage').get('output_tokens')
|
120
|
+
self._finish_reason = chunked.get('delta').get('stop_reason')
|
121
|
+
|
122
|
+
return chunk
|
123
|
+
except StopAsyncIteration:
|
124
|
+
# Handling exception ensure observability without disrupting operation
|
125
|
+
try:
|
126
|
+
self._end_time = time.time()
|
127
|
+
if len(self._timestamps) > 1:
|
128
|
+
self._tbt = calculate_tbt(self._timestamps)
|
129
|
+
|
130
|
+
# Format 'messages' into a single string
|
131
|
+
message_prompt = self._kwargs.get("messages", "")
|
132
|
+
formatted_messages = []
|
133
|
+
for message in message_prompt:
|
134
|
+
role = message["role"]
|
135
|
+
content = message["content"]
|
136
|
+
|
137
|
+
if isinstance(content, list):
|
138
|
+
content_str_list = []
|
139
|
+
for item in content:
|
140
|
+
if item["type"] == "text":
|
141
|
+
content_str_list.append(f'text: {item["text"]}')
|
142
|
+
elif (item["type"] == "image_url" and
|
143
|
+
not item["image_url"]["url"].startswith("data:")):
|
144
|
+
content_str_list.append(f'image_url: {item["image_url"]["url"]}')
|
145
|
+
content_str = ", ".join(content_str_list)
|
146
|
+
formatted_messages.append(f"{role}: {content_str}")
|
147
|
+
else:
|
148
|
+
formatted_messages.append(f"{role}: {content}")
|
149
|
+
prompt = "\n".join(formatted_messages)
|
150
|
+
|
151
|
+
request_model = self._kwargs.get("model", "claude-3-5-sonnet-latest")
|
152
|
+
|
153
|
+
# Calculate cost of the operation
|
154
|
+
cost = get_chat_model_cost(request_model,
|
155
|
+
pricing_info, self._input_tokens,
|
156
|
+
self._output_tokens)
|
157
|
+
|
158
|
+
# Set Span attributes (OTel Semconv)
|
159
|
+
self._span.set_attribute(TELEMETRY_SDK_NAME, "openlit")
|
160
|
+
self._span.set_attribute(SemanticConvetion.GEN_AI_OPERATION,
|
161
|
+
SemanticConvetion.GEN_AI_OPERATION_TYPE_CHAT)
|
162
|
+
self._span.set_attribute(SemanticConvetion.GEN_AI_SYSTEM,
|
163
|
+
SemanticConvetion.GEN_AI_SYSTEM_ANTHROPIC)
|
164
|
+
self._span.set_attribute(SemanticConvetion.GEN_AI_REQUEST_MODEL,
|
165
|
+
request_model)
|
166
|
+
self._span.set_attribute(SemanticConvetion.SERVER_PORT,
|
167
|
+
self._server_port)
|
168
|
+
self._span.set_attribute(SemanticConvetion.GEN_AI_REQUEST_MAX_TOKENS,
|
169
|
+
self._kwargs.get("max_tokens", -1))
|
170
|
+
self._span.set_attribute(SemanticConvetion.GEN_AI_REQUEST_STOP_SEQUENCES,
|
171
|
+
self._kwargs.get("stop_sequences", []))
|
172
|
+
self._span.set_attribute(SemanticConvetion.GEN_AI_REQUEST_TEMPERATURE,
|
173
|
+
self._kwargs.get("temperature", 1.0))
|
174
|
+
self._span.set_attribute(SemanticConvetion.GEN_AI_REQUEST_TOP_K,
|
175
|
+
self._kwargs.get("top_k", 1.0))
|
176
|
+
self._span.set_attribute(SemanticConvetion.GEN_AI_REQUEST_TOP_P,
|
177
|
+
self._kwargs.get("top_p", 1.0))
|
178
|
+
self._span.set_attribute(SemanticConvetion.GEN_AI_RESPONSE_FINISH_REASON,
|
179
|
+
[self._finish_reason])
|
180
|
+
self._span.set_attribute(SemanticConvetion.GEN_AI_RESPONSE_ID,
|
181
|
+
self._response_id)
|
182
|
+
self._span.set_attribute(SemanticConvetion.GEN_AI_RESPONSE_MODEL,
|
183
|
+
self._response_model)
|
184
|
+
self._span.set_attribute(SemanticConvetion.GEN_AI_USAGE_INPUT_TOKENS,
|
185
|
+
self._input_tokens)
|
186
|
+
self._span.set_attribute(SemanticConvetion.GEN_AI_USAGE_OUTPUT_TOKENS,
|
187
|
+
self._output_tokens)
|
188
|
+
self._span.set_attribute(SemanticConvetion.SERVER_ADDRESS,
|
189
|
+
self._server_address)
|
190
|
+
if isinstance(self._llmresponse, str):
|
191
|
+
self._span.set_attribute(SemanticConvetion.GEN_AI_OUTPUT_TYPE,
|
192
|
+
"text")
|
193
|
+
else:
|
194
|
+
self._span.set_attribute(SemanticConvetion.GEN_AI_OUTPUT_TYPE,
|
195
|
+
"json")
|
196
|
+
|
197
|
+
# Set Span attributes (Extra)
|
198
|
+
self._span.set_attribute(DEPLOYMENT_ENVIRONMENT,
|
199
|
+
environment)
|
200
|
+
self._span.set_attribute(SERVICE_NAME,
|
201
|
+
application_name)
|
202
|
+
self._span.set_attribute(SemanticConvetion.GEN_AI_REQUEST_IS_STREAM,
|
203
|
+
True)
|
204
|
+
self._span.set_attribute(SemanticConvetion.GEN_AI_USAGE_TOTAL_TOKENS,
|
205
|
+
self._input_tokens + self._output_tokens)
|
206
|
+
self._span.set_attribute(SemanticConvetion.GEN_AI_USAGE_COST,
|
207
|
+
cost)
|
208
|
+
self._span.set_attribute(SemanticConvetion.GEN_AI_SERVER_TBT,
|
209
|
+
self._tbt)
|
210
|
+
self._span.set_attribute(SemanticConvetion.GEN_AI_SERVER_TTFT,
|
211
|
+
self._ttft)
|
212
|
+
self._span.set_attribute(SemanticConvetion.GEN_AI_SDK_VERSION,
|
213
|
+
version)
|
214
|
+
if trace_content:
|
215
|
+
self._span.add_event(
|
216
|
+
name=SemanticConvetion.GEN_AI_CONTENT_PROMPT_EVENT,
|
217
|
+
attributes={
|
218
|
+
SemanticConvetion.GEN_AI_CONTENT_PROMPT: prompt,
|
219
|
+
},
|
220
|
+
)
|
221
|
+
self._span.add_event(
|
222
|
+
name=SemanticConvetion.GEN_AI_CONTENT_COMPLETION_EVENT,
|
223
|
+
attributes={
|
224
|
+
SemanticConvetion.GEN_AI_CONTENT_COMPLETION: self._llmresponse,
|
225
|
+
},
|
226
|
+
)
|
227
|
+
self._span.set_status(Status(StatusCode.OK))
|
228
|
+
|
229
|
+
if disable_metrics is False:
|
230
|
+
attributes = create_metrics_attributes(
|
231
|
+
service_name=application_name,
|
232
|
+
deployment_environment=environment,
|
233
|
+
operation=SemanticConvetion.GEN_AI_OPERATION_TYPE_CHAT,
|
234
|
+
system=SemanticConvetion.GEN_AI_SYSTEM_ANTHROPIC,
|
235
|
+
request_model=request_model,
|
236
|
+
server_address=self._server_address,
|
237
|
+
server_port=self._server_port,
|
238
|
+
response_model=self._response_model,
|
239
|
+
)
|
240
|
+
|
241
|
+
metrics["genai_client_usage_tokens"].record(
|
242
|
+
self._input_tokens + self._output_tokens, attributes
|
243
|
+
)
|
244
|
+
metrics["genai_client_operation_duration"].record(
|
245
|
+
self._end_time - self._start_time, attributes
|
246
|
+
)
|
247
|
+
metrics["genai_server_tbt"].record(
|
248
|
+
self._tbt, attributes
|
249
|
+
)
|
250
|
+
metrics["genai_server_ttft"].record(
|
251
|
+
self._ttft, attributes
|
252
|
+
)
|
253
|
+
metrics["genai_requests"].add(1, attributes)
|
254
|
+
metrics["genai_completion_tokens"].add(self._output_tokens, attributes)
|
255
|
+
metrics["genai_prompt_tokens"].add(self._input_tokens, attributes)
|
256
|
+
metrics["genai_cost"].record(cost, attributes)
|
257
|
+
|
258
|
+
except Exception as e:
|
259
|
+
handle_exception(self._span, e)
|
260
|
+
logger.error("Error in trace creation: %s", e)
|
261
|
+
finally:
|
262
|
+
self._span.end()
|
263
|
+
raise
|
264
|
+
|
33
265
|
async def wrapper(wrapped, instance, args, kwargs):
|
34
266
|
"""
|
35
267
|
Wraps the 'messages' API call to add telemetry.
|
@@ -49,147 +281,27 @@ def async_messages(gen_ai_endpoint, version, environment, application_name,
|
|
49
281
|
|
50
282
|
# Check if streaming is enabled for the API call
|
51
283
|
streaming = kwargs.get("stream", False)
|
284
|
+
server_address, server_port = set_server_address_and_port(instance, "api.anthropic.com", 443)
|
285
|
+
request_model = kwargs.get("model", "claude-3-5-sonnet-latest")
|
286
|
+
|
287
|
+
span_name = f"{SemanticConvetion.GEN_AI_OPERATION_TYPE_CHAT} {request_model}"
|
52
288
|
|
53
289
|
# pylint: disable=no-else-return
|
54
290
|
if streaming:
|
55
291
|
# Special handling for streaming response to accommodate the nature of data flow
|
56
|
-
|
57
|
-
|
58
|
-
# Placeholder for aggregating streaming response
|
59
|
-
llmresponse = ""
|
60
|
-
|
61
|
-
# Loop through streaming events capturing relevant details
|
62
|
-
async for event in await wrapped(*args, **kwargs):
|
63
|
-
|
64
|
-
# Collect message IDs and input token from events
|
65
|
-
if event.type == "message_start":
|
66
|
-
response_id = event.message.id
|
67
|
-
prompt_tokens = event.message.usage.input_tokens
|
68
|
-
|
69
|
-
# Aggregate response content
|
70
|
-
if event.type == "content_block_delta":
|
71
|
-
llmresponse += event.delta.text
|
72
|
-
|
73
|
-
# Collect output tokens and stop reason from events
|
74
|
-
if event.type == "message_delta":
|
75
|
-
completion_tokens = event.usage.output_tokens
|
76
|
-
finish_reason = event.delta.stop_reason
|
77
|
-
yield event
|
78
|
-
|
79
|
-
# Handling exception ensure observability without disrupting operation
|
80
|
-
try:
|
81
|
-
# Format 'messages' into a single string
|
82
|
-
message_prompt = kwargs.get("messages", "")
|
83
|
-
formatted_messages = []
|
84
|
-
for message in message_prompt:
|
85
|
-
role = message["role"]
|
86
|
-
content = message["content"]
|
87
|
-
|
88
|
-
if isinstance(content, list):
|
89
|
-
content_str = ", ".join(
|
90
|
-
# pylint: disable=line-too-long
|
91
|
-
f'{item["type"]}: {item["text"] if "text" in item else item["image_url"]}'
|
92
|
-
if "type" in item else f'text: {item["text"]}'
|
93
|
-
for item in content
|
94
|
-
)
|
95
|
-
formatted_messages.append(f"{role}: {content_str}")
|
96
|
-
else:
|
97
|
-
formatted_messages.append(f"{role}: {content}")
|
98
|
-
prompt = "\n".join(formatted_messages)
|
99
|
-
|
100
|
-
# Calculate cost of the operation
|
101
|
-
cost = get_chat_model_cost(
|
102
|
-
kwargs.get("model", "claude-3-sonnet-20240229"),
|
103
|
-
pricing_info, prompt_tokens, completion_tokens
|
104
|
-
)
|
292
|
+
awaited_wrapped = await wrapped(*args, **kwargs)
|
293
|
+
span = tracer.start_span(span_name, kind=SpanKind.CLIENT)
|
105
294
|
|
106
|
-
|
107
|
-
span.set_attribute(TELEMETRY_SDK_NAME, "openlit")
|
108
|
-
span.set_attribute(SemanticConvetion.GEN_AI_SYSTEM,
|
109
|
-
SemanticConvetion.GEN_AI_SYSTEM_ANTHROPIC)
|
110
|
-
span.set_attribute(SemanticConvetion.GEN_AI_TYPE,
|
111
|
-
SemanticConvetion.GEN_AI_TYPE_CHAT)
|
112
|
-
span.set_attribute(SemanticConvetion.GEN_AI_ENDPOINT,
|
113
|
-
gen_ai_endpoint)
|
114
|
-
span.set_attribute(SemanticConvetion.GEN_AI_RESPONSE_ID,
|
115
|
-
response_id)
|
116
|
-
span.set_attribute(SemanticConvetion.GEN_AI_ENVIRONMENT,
|
117
|
-
environment)
|
118
|
-
span.set_attribute(SemanticConvetion.GEN_AI_APPLICATION_NAME,
|
119
|
-
application_name)
|
120
|
-
span.set_attribute(SemanticConvetion.GEN_AI_REQUEST_MODEL,
|
121
|
-
kwargs.get("model", "claude-3-sonnet-20240229"))
|
122
|
-
span.set_attribute(SemanticConvetion.GEN_AI_REQUEST_MAX_TOKENS,
|
123
|
-
kwargs.get("max_tokens", -1))
|
124
|
-
span.set_attribute(SemanticConvetion.GEN_AI_REQUEST_IS_STREAM,
|
125
|
-
True)
|
126
|
-
span.set_attribute(SemanticConvetion.GEN_AI_REQUEST_TEMPERATURE,
|
127
|
-
kwargs.get("temperature", 1.0))
|
128
|
-
span.set_attribute(SemanticConvetion.GEN_AI_REQUEST_TOP_P,
|
129
|
-
kwargs.get("top_p", ""))
|
130
|
-
span.set_attribute(SemanticConvetion.GEN_AI_REQUEST_TOP_K,
|
131
|
-
kwargs.get("top_k", ""))
|
132
|
-
span.set_attribute(SemanticConvetion.GEN_AI_RESPONSE_FINISH_REASON,
|
133
|
-
[finish_reason])
|
134
|
-
span.set_attribute(SemanticConvetion.GEN_AI_USAGE_PROMPT_TOKENS,
|
135
|
-
prompt_tokens)
|
136
|
-
span.set_attribute(SemanticConvetion.GEN_AI_USAGE_COMPLETION_TOKENS,
|
137
|
-
completion_tokens)
|
138
|
-
span.set_attribute(SemanticConvetion.GEN_AI_USAGE_TOTAL_TOKENS,
|
139
|
-
prompt_tokens + completion_tokens)
|
140
|
-
span.set_attribute(SemanticConvetion.GEN_AI_USAGE_COST,
|
141
|
-
cost)
|
142
|
-
if trace_content:
|
143
|
-
span.add_event(
|
144
|
-
name=SemanticConvetion.GEN_AI_CONTENT_PROMPT_EVENT,
|
145
|
-
attributes={
|
146
|
-
SemanticConvetion.GEN_AI_CONTENT_PROMPT: prompt,
|
147
|
-
},
|
148
|
-
)
|
149
|
-
span.add_event(
|
150
|
-
name=SemanticConvetion.GEN_AI_CONTENT_COMPLETION_EVENT,
|
151
|
-
attributes={
|
152
|
-
SemanticConvetion.GEN_AI_CONTENT_COMPLETION: llmresponse,
|
153
|
-
},
|
154
|
-
)
|
155
|
-
|
156
|
-
span.set_status(Status(StatusCode.OK))
|
157
|
-
|
158
|
-
if disable_metrics is False:
|
159
|
-
attributes = {
|
160
|
-
TELEMETRY_SDK_NAME:
|
161
|
-
"openlit",
|
162
|
-
SemanticConvetion.GEN_AI_APPLICATION_NAME:
|
163
|
-
application_name,
|
164
|
-
SemanticConvetion.GEN_AI_SYSTEM:
|
165
|
-
SemanticConvetion.GEN_AI_SYSTEM_ANTHROPIC,
|
166
|
-
SemanticConvetion.GEN_AI_ENVIRONMENT:
|
167
|
-
environment,
|
168
|
-
SemanticConvetion.GEN_AI_TYPE:
|
169
|
-
SemanticConvetion.GEN_AI_TYPE_CHAT,
|
170
|
-
SemanticConvetion.GEN_AI_REQUEST_MODEL:
|
171
|
-
kwargs.get("model", "claude-3-sonnet-20240229")
|
172
|
-
}
|
173
|
-
|
174
|
-
metrics["genai_requests"].add(1, attributes)
|
175
|
-
metrics["genai_total_tokens"].add(
|
176
|
-
prompt_tokens + completion_tokens, attributes
|
177
|
-
)
|
178
|
-
metrics["genai_completion_tokens"].add(completion_tokens, attributes)
|
179
|
-
metrics["genai_prompt_tokens"].add(prompt_tokens, attributes)
|
180
|
-
metrics["genai_cost"].record(cost, attributes)
|
181
|
-
|
182
|
-
except Exception as e:
|
183
|
-
handle_exception(span, e)
|
184
|
-
logger.error("Error in trace creation: %s", e)
|
185
|
-
|
186
|
-
return stream_generator()
|
295
|
+
return TracedASyncStream(awaited_wrapped, span, kwargs, server_address, server_port)
|
187
296
|
|
188
297
|
# Handling for non-streaming responses
|
189
298
|
else:
|
190
|
-
with tracer.start_as_current_span(
|
299
|
+
with tracer.start_as_current_span(span_name, kind=SpanKind.CLIENT) as span:
|
300
|
+
start_time = time.time()
|
191
301
|
response = await wrapped(*args, **kwargs)
|
302
|
+
end_time = time.time()
|
192
303
|
|
304
|
+
response_dict = response_as_dict(response)
|
193
305
|
try:
|
194
306
|
# Format 'messages' into a single string
|
195
307
|
message_prompt = kwargs.get("messages", "")
|
@@ -200,7 +312,6 @@ def async_messages(gen_ai_endpoint, version, environment, application_name,
|
|
200
312
|
|
201
313
|
if isinstance(content, list):
|
202
314
|
content_str = ", ".join(
|
203
|
-
# pylint: disable=line-too-long
|
204
315
|
f'{item["type"]}: {item["text"] if "text" in item else item["image_url"]}'
|
205
316
|
if "type" in item else f'text: {item["text"]}'
|
206
317
|
for item in content
|
@@ -210,48 +321,71 @@ def async_messages(gen_ai_endpoint, version, environment, application_name,
|
|
210
321
|
formatted_messages.append(f"{role}: {content}")
|
211
322
|
prompt = "\n".join(formatted_messages)
|
212
323
|
|
324
|
+
input_tokens = response_dict.get('usage').get('input_tokens')
|
325
|
+
output_tokens = response_dict.get('usage').get('output_tokens')
|
326
|
+
|
213
327
|
# Calculate cost of the operation
|
214
|
-
cost = get_chat_model_cost(
|
215
|
-
pricing_info,
|
216
|
-
|
328
|
+
cost = get_chat_model_cost(request_model,
|
329
|
+
pricing_info, input_tokens,
|
330
|
+
output_tokens)
|
217
331
|
|
218
|
-
|
332
|
+
llm_response = ""
|
333
|
+
for i in range(len(response_dict.get('content'))):
|
334
|
+
if response_dict.get('content')[i].get('type') == 'text':
|
335
|
+
llm_response = response_dict.get('content')[i].get('text')
|
336
|
+
|
337
|
+
# Set Span attributes (OTel Semconv)
|
219
338
|
span.set_attribute(TELEMETRY_SDK_NAME, "openlit")
|
339
|
+
span.set_attribute(SemanticConvetion.GEN_AI_OPERATION,
|
340
|
+
SemanticConvetion.GEN_AI_OPERATION_TYPE_CHAT)
|
220
341
|
span.set_attribute(SemanticConvetion.GEN_AI_SYSTEM,
|
221
342
|
SemanticConvetion.GEN_AI_SYSTEM_ANTHROPIC)
|
222
|
-
span.set_attribute(SemanticConvetion.GEN_AI_TYPE,
|
223
|
-
SemanticConvetion.GEN_AI_TYPE_CHAT)
|
224
|
-
span.set_attribute(SemanticConvetion.GEN_AI_ENDPOINT,
|
225
|
-
gen_ai_endpoint)
|
226
|
-
span.set_attribute(SemanticConvetion.GEN_AI_RESPONSE_ID,
|
227
|
-
response.id)
|
228
|
-
span.set_attribute(SemanticConvetion.GEN_AI_ENVIRONMENT,
|
229
|
-
environment)
|
230
|
-
span.set_attribute(SemanticConvetion.GEN_AI_APPLICATION_NAME,
|
231
|
-
application_name)
|
232
343
|
span.set_attribute(SemanticConvetion.GEN_AI_REQUEST_MODEL,
|
233
|
-
|
344
|
+
request_model)
|
345
|
+
span.set_attribute(SemanticConvetion.SERVER_PORT,
|
346
|
+
server_port)
|
234
347
|
span.set_attribute(SemanticConvetion.GEN_AI_REQUEST_MAX_TOKENS,
|
235
348
|
kwargs.get("max_tokens", -1))
|
236
|
-
span.set_attribute(SemanticConvetion.
|
237
|
-
|
349
|
+
span.set_attribute(SemanticConvetion.GEN_AI_REQUEST_STOP_SEQUENCES,
|
350
|
+
kwargs.get("stop_sequences", []))
|
238
351
|
span.set_attribute(SemanticConvetion.GEN_AI_REQUEST_TEMPERATURE,
|
239
352
|
kwargs.get("temperature", 1.0))
|
240
|
-
span.set_attribute(SemanticConvetion.GEN_AI_REQUEST_TOP_P,
|
241
|
-
kwargs.get("top_p", ""))
|
242
353
|
span.set_attribute(SemanticConvetion.GEN_AI_REQUEST_TOP_K,
|
243
|
-
kwargs.get("top_k",
|
354
|
+
kwargs.get("top_k", 1.0))
|
355
|
+
span.set_attribute(SemanticConvetion.GEN_AI_REQUEST_TOP_P,
|
356
|
+
kwargs.get("top_p", 1.0))
|
244
357
|
span.set_attribute(SemanticConvetion.GEN_AI_RESPONSE_FINISH_REASON,
|
245
|
-
[
|
246
|
-
span.set_attribute(SemanticConvetion.
|
247
|
-
|
248
|
-
span.set_attribute(SemanticConvetion.
|
249
|
-
|
358
|
+
[response_dict.get('stop_reason')])
|
359
|
+
span.set_attribute(SemanticConvetion.GEN_AI_RESPONSE_ID,
|
360
|
+
response_dict.get('id'))
|
361
|
+
span.set_attribute(SemanticConvetion.GEN_AI_RESPONSE_MODEL,
|
362
|
+
response_dict.get('model'))
|
363
|
+
span.set_attribute(SemanticConvetion.GEN_AI_USAGE_INPUT_TOKENS,
|
364
|
+
input_tokens)
|
365
|
+
span.set_attribute(SemanticConvetion.GEN_AI_USAGE_OUTPUT_TOKENS,
|
366
|
+
output_tokens)
|
367
|
+
span.set_attribute(SemanticConvetion.SERVER_ADDRESS,
|
368
|
+
server_address)
|
369
|
+
|
370
|
+
span.set_attribute(SemanticConvetion.GEN_AI_OUTPUT_TYPE,
|
371
|
+
response_dict.get('content')[0].get('type'))
|
372
|
+
|
373
|
+
# Set Span attributes (Extra)
|
374
|
+
span.set_attribute(DEPLOYMENT_ENVIRONMENT,
|
375
|
+
environment)
|
376
|
+
span.set_attribute(SERVICE_NAME,
|
377
|
+
application_name)
|
378
|
+
span.set_attribute(SemanticConvetion.GEN_AI_REQUEST_IS_STREAM,
|
379
|
+
False)
|
250
380
|
span.set_attribute(SemanticConvetion.GEN_AI_USAGE_TOTAL_TOKENS,
|
251
|
-
|
252
|
-
response.usage.output_tokens)
|
381
|
+
input_tokens + output_tokens)
|
253
382
|
span.set_attribute(SemanticConvetion.GEN_AI_USAGE_COST,
|
254
383
|
cost)
|
384
|
+
span.set_attribute(SemanticConvetion.GEN_AI_SERVER_TTFT,
|
385
|
+
end_time - start_time)
|
386
|
+
span.set_attribute(SemanticConvetion.GEN_AI_SDK_VERSION,
|
387
|
+
version)
|
388
|
+
|
255
389
|
if trace_content:
|
256
390
|
span.add_event(
|
257
391
|
name=SemanticConvetion.GEN_AI_CONTENT_PROMPT_EVENT,
|
@@ -262,37 +396,36 @@ def async_messages(gen_ai_endpoint, version, environment, application_name,
|
|
262
396
|
span.add_event(
|
263
397
|
name=SemanticConvetion.GEN_AI_CONTENT_COMPLETION_EVENT,
|
264
398
|
attributes={
|
265
|
-
|
266
|
-
SemanticConvetion.GEN_AI_CONTENT_COMPLETION: response.content[0].text if response.content else "",
|
399
|
+
SemanticConvetion.GEN_AI_CONTENT_COMPLETION: llm_response,
|
267
400
|
},
|
268
401
|
)
|
269
402
|
|
270
403
|
span.set_status(Status(StatusCode.OK))
|
271
404
|
|
272
405
|
if disable_metrics is False:
|
273
|
-
attributes =
|
274
|
-
|
275
|
-
|
276
|
-
SemanticConvetion.
|
277
|
-
|
278
|
-
|
279
|
-
|
280
|
-
|
281
|
-
|
282
|
-
|
283
|
-
SemanticConvetion.GEN_AI_TYPE_CHAT,
|
284
|
-
SemanticConvetion.GEN_AI_REQUEST_MODEL:
|
285
|
-
kwargs.get("model", "claude-3-sonnet-20240229")
|
286
|
-
}
|
406
|
+
attributes = create_metrics_attributes(
|
407
|
+
service_name=application_name,
|
408
|
+
deployment_environment=environment,
|
409
|
+
operation=SemanticConvetion.GEN_AI_OPERATION_TYPE_CHAT,
|
410
|
+
system=SemanticConvetion.GEN_AI_SYSTEM_ANTHROPIC,
|
411
|
+
request_model=request_model,
|
412
|
+
server_address=server_address,
|
413
|
+
server_port=server_port,
|
414
|
+
response_model=response_dict.get('model'),
|
415
|
+
)
|
287
416
|
|
417
|
+
metrics["genai_client_usage_tokens"].record(
|
418
|
+
input_tokens + output_tokens, attributes
|
419
|
+
)
|
420
|
+
metrics["genai_client_operation_duration"].record(
|
421
|
+
end_time - start_time, attributes
|
422
|
+
)
|
423
|
+
metrics["genai_server_ttft"].record(
|
424
|
+
end_time - start_time, attributes
|
425
|
+
)
|
288
426
|
metrics["genai_requests"].add(1, attributes)
|
289
|
-
metrics["
|
290
|
-
|
291
|
-
response.usage.output_tokens, attributes)
|
292
|
-
metrics["genai_completion_tokens"].add(
|
293
|
-
response.usage.output_tokens, attributes)
|
294
|
-
metrics["genai_prompt_tokens"].add(
|
295
|
-
response.usage.input_tokens, attributes)
|
427
|
+
metrics["genai_completion_tokens"].add(output_tokens, attributes)
|
428
|
+
metrics["genai_prompt_tokens"].add(input_tokens, attributes)
|
296
429
|
metrics["genai_cost"].record(cost, attributes)
|
297
430
|
|
298
431
|
# Return original response
|
@@ -34,7 +34,7 @@ class AssemblyAIInstrumentor(BaseInstrumentor):
|
|
34
34
|
wrap_function_wrapper(
|
35
35
|
"assemblyai.transcriber",
|
36
36
|
"Transcriber.transcribe",
|
37
|
-
transcribe(
|
37
|
+
transcribe(version, environment, application_name,
|
38
38
|
tracer, pricing_info, trace_content, metrics, disable_metrics),
|
39
39
|
)
|
40
40
|
|