openlit 1.34.20__py3-none-any.whl → 1.34.22__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,204 @@
1
+ """
2
+ VertexAI OpenTelemetry instrumentation utility functions
3
+ """
4
+ import time
5
+
6
+ from opentelemetry.trace import Status, StatusCode
7
+
8
+ from openlit.__helpers import (
9
+ calculate_ttft,
10
+ calculate_tbt,
11
+ get_chat_model_cost,
12
+ record_completion_metrics,
13
+ common_span_attributes,
14
+ )
15
+ from openlit.semcov import SemanticConvention
16
+
17
+ def format_content(contents):
18
+ """
19
+ Format the VertexAI contents into a string for span events.
20
+ """
21
+
22
+ if not contents:
23
+ return ""
24
+
25
+ formatted_messages = []
26
+ for content in contents:
27
+ role = content.role
28
+ parts = content.parts
29
+ content_str = []
30
+
31
+ for part in parts:
32
+ # Collect relevant fields and handle each type of data that Part could contain
33
+ if part.text:
34
+ content_str.append(f"text: {part.text}")
35
+ if part.video_metadata:
36
+ content_str.append(f"video_metadata: {part.video_metadata}")
37
+ if part.thought:
38
+ content_str.append(f"thought: {part.thought}")
39
+ if part.code_execution_result:
40
+ content_str.append(f"code_execution_result: {part.code_execution_result}")
41
+ if part.executable_code:
42
+ content_str.append(f"executable_code: {part.executable_code}")
43
+ if part.file_data:
44
+ content_str.append(f"file_data: {part.file_data}")
45
+ if part.function_call:
46
+ content_str.append(f"function_call: {part.function_call}")
47
+ if part.function_response:
48
+ content_str.append(f"function_response: {part.function_response}")
49
+ if part.inline_data:
50
+ content_str.append(f"inline_data: {part.inline_data}")
51
+
52
+ formatted_messages.append(f"{role}: {', '.join(content_str)}")
53
+
54
+ return "\n".join(formatted_messages)
55
+
56
+ def process_chunk(scope, chunk):
57
+ """
58
+ Process a chunk of response data and update state.
59
+ """
60
+
61
+ end_time = time.time()
62
+ # Record the timestamp for the current chunk
63
+ scope._timestamps.append(end_time)
64
+
65
+ if len(scope._timestamps) == 1:
66
+ # Calculate time to first chunk
67
+ scope._ttft = calculate_ttft(scope._timestamps, scope._start_time)
68
+
69
+ # Aggregate response content
70
+ scope._llmresponse += str(chunk.text)
71
+ scope._input_tokens = chunk.usage_metadata.prompt_token_count
72
+ scope._output_tokens = chunk.usage_metadata.candidates_token_count
73
+
74
+ def common_chat_logic(scope, pricing_info, environment, application_name, metrics,
75
+ capture_message_content, disable_metrics, version, is_stream):
76
+ """
77
+ Process chat request and generate Telemetry
78
+ """
79
+
80
+ scope._end_time = time.time()
81
+ if len(scope._timestamps) > 1:
82
+ scope._tbt = calculate_tbt(scope._timestamps)
83
+
84
+ # Format content using VertexAI-specific logic
85
+ contents = scope._kwargs.get("contents", [])
86
+ formatted_messages = format_content(contents)
87
+ prompt = formatted_messages or str(scope._args[0][0])
88
+
89
+ cost = get_chat_model_cost(scope._request_model, pricing_info, scope._input_tokens, scope._output_tokens)
90
+
91
+ # Common Span Attributes
92
+ common_span_attributes(scope,
93
+ SemanticConvention.GEN_AI_OPERATION_TYPE_CHAT, SemanticConvention.GEN_AI_SYSTEM_VERTEXAI,
94
+ scope._server_address, scope._server_port, scope._request_model, scope._request_model,
95
+ environment, application_name, is_stream, scope._tbt, scope._ttft, version)
96
+
97
+ # Span Attributes for Request parameters (VertexAI-specific)
98
+ inference_config = scope._kwargs.get("generation_config", {})
99
+
100
+ # List of attributes and their config keys
101
+ attributes = [
102
+ (SemanticConvention.GEN_AI_REQUEST_FREQUENCY_PENALTY, "frequency_penalty"),
103
+ (SemanticConvention.GEN_AI_REQUEST_MAX_TOKENS, "max_output_tokens"),
104
+ (SemanticConvention.GEN_AI_REQUEST_PRESENCE_PENALTY, "presence_penalty"),
105
+ (SemanticConvention.GEN_AI_REQUEST_STOP_SEQUENCES, "stop_sequences"),
106
+ (SemanticConvention.GEN_AI_REQUEST_TEMPERATURE, "temperature"),
107
+ (SemanticConvention.GEN_AI_REQUEST_TOP_P, "top_p"),
108
+ (SemanticConvention.GEN_AI_REQUEST_TOP_K, "top_k"),
109
+ ]
110
+
111
+ # Set each attribute if the corresponding value exists and is not None
112
+ for attribute, key in attributes:
113
+ value = inference_config.get(key)
114
+ if value is not None:
115
+ scope._span.set_attribute(attribute, value)
116
+
117
+ # Span Attributes for Response parameters
118
+ scope._span.set_attribute(SemanticConvention.GEN_AI_OUTPUT_TYPE, "text" if isinstance(scope._llmresponse, str) else "json")
119
+
120
+ # Span Attributes for Cost and Tokens
121
+ scope._span.set_attribute(SemanticConvention.GEN_AI_USAGE_INPUT_TOKENS, scope._input_tokens)
122
+ scope._span.set_attribute(SemanticConvention.GEN_AI_USAGE_OUTPUT_TOKENS, scope._output_tokens)
123
+ scope._span.set_attribute(SemanticConvention.GEN_AI_CLIENT_TOKEN_USAGE, scope._input_tokens + scope._output_tokens)
124
+ scope._span.set_attribute(SemanticConvention.GEN_AI_USAGE_COST, cost)
125
+
126
+ # Span Attributes for Content
127
+ if capture_message_content:
128
+ scope._span.set_attribute(SemanticConvention.GEN_AI_CONTENT_PROMPT, prompt)
129
+ scope._span.set_attribute(SemanticConvention.GEN_AI_CONTENT_COMPLETION, scope._llmresponse)
130
+
131
+ # To be removed once the change to span_attributes (from span events) is complete
132
+ scope._span.add_event(
133
+ name=SemanticConvention.GEN_AI_CONTENT_PROMPT_EVENT,
134
+ attributes={
135
+ SemanticConvention.GEN_AI_CONTENT_PROMPT: prompt,
136
+ },
137
+ )
138
+ scope._span.add_event(
139
+ name=SemanticConvention.GEN_AI_CONTENT_COMPLETION_EVENT,
140
+ attributes={
141
+ SemanticConvention.GEN_AI_CONTENT_COMPLETION: scope._llmresponse,
142
+ },
143
+ )
144
+
145
+ scope._span.set_status(Status(StatusCode.OK))
146
+
147
+ # Record metrics
148
+ if not disable_metrics:
149
+ record_completion_metrics(metrics, SemanticConvention.GEN_AI_OPERATION_TYPE_CHAT, SemanticConvention.GEN_AI_SYSTEM_VERTEXAI,
150
+ scope._server_address, scope._server_port, scope._request_model, scope._request_model, environment,
151
+ application_name, scope._start_time, scope._end_time, scope._input_tokens, scope._output_tokens,
152
+ cost, scope._tbt, scope._ttft)
153
+
154
+ def process_streaming_chat_response(scope, pricing_info, environment, application_name, metrics,
155
+ capture_message_content=False, disable_metrics=False, version=""):
156
+ """
157
+ Process streaming chat response and generate telemetry.
158
+ """
159
+
160
+ common_chat_logic(scope, pricing_info, environment, application_name, metrics,
161
+ capture_message_content, disable_metrics, version, is_stream=True)
162
+
163
+ def process_chat_response(response, request_model, pricing_info, server_port, server_address,
164
+ environment, application_name, metrics, start_time,
165
+ span, capture_message_content=False, disable_metrics=False, version="1.0.0", **kwargs):
166
+ """
167
+ Process non-streaming chat response and generate telemetry.
168
+ """
169
+
170
+ scope = type("GenericScope", (), {})()
171
+
172
+ scope._start_time = start_time
173
+ scope._end_time = time.time()
174
+ scope._span = span
175
+ scope._llmresponse = response.text
176
+ scope._input_tokens = response.usage_metadata.prompt_token_count
177
+ scope._output_tokens = response.usage_metadata.candidates_token_count
178
+ scope._timestamps = []
179
+ scope._ttft, scope._tbt = scope._end_time - scope._start_time, 0
180
+ scope._server_address, scope._server_port = server_address, server_port
181
+ scope._request_model = request_model
182
+ scope._kwargs = kwargs
183
+ scope._args = [kwargs.get("contents", [])]
184
+
185
+ common_chat_logic(scope, pricing_info, environment, application_name, metrics,
186
+ capture_message_content, disable_metrics, version, is_stream=False)
187
+
188
+ return response
189
+
190
+ def extract_vertexai_details(instance):
191
+ """
192
+ Extract VertexAI-specific details like location and model name.
193
+ """
194
+ try:
195
+ location = instance._model._location
196
+ request_model = "/".join(instance._model._model_name.split("/")[3:])
197
+ except:
198
+ location = instance._location
199
+ request_model = "/".join(instance._model_name.split("/")[3:])
200
+
201
+ server_address = location + "-aiplatform.googleapis.com"
202
+ server_port = 443
203
+
204
+ return server_address, server_port, request_model