|
11 | 11 | from sentry_sdk.utils import ( |
12 | 12 | capture_internal_exceptions, |
13 | 13 | event_from_exception, |
| 14 | + safe_serialize, |
14 | 15 | ) |
15 | 16 |
|
16 | 17 | from typing import TYPE_CHECKING |
@@ -183,24 +184,50 @@ def _new_chat_completion_common(f, *args, **kwargs): |
183 | 184 | ) |
184 | 185 | span.__enter__() |
185 | 186 |
|
| 187 | + # Common attributes |
| 188 | + set_data_normalized(span, SPANDATA.GEN_AI_SYSTEM, "openai") |
| 189 | + set_data_normalized(span, SPANDATA.GEN_AI_REQUEST_MODEL, model) |
| 190 | + set_data_normalized(span, SPANDATA.GEN_AI_OPERATION_NAME, "chat") |
| 191 | + set_data_normalized(span, SPANDATA.AI_STREAMING, streaming) |
| 192 | + |
| 193 | + # Optional attributes |
| 194 | + max_tokens = kwargs.get("max_tokens") |
| 195 | + if max_tokens is not None: |
| 196 | + set_data_normalized(span, SPANDATA.GEN_AI_REQUEST_MAX_TOKENS, max_tokens) |
| 197 | + |
| 198 | + presence_penalty = kwargs.get("presence_penalty") |
| 199 | + if presence_penalty is not None: |
| 200 | + set_data_normalized( |
| 201 | + span, SPANDATA.GEN_AI_REQUEST_PRESENCE_PENALTY, presence_penalty |
| 202 | + ) |
| 203 | + |
| 204 | + temperature = kwargs.get("temperature") |
| 205 | + if temperature is not None: |
| 206 | + set_data_normalized(span, SPANDATA.GEN_AI_REQUEST_TEMPERATURE, temperature) |
| 207 | + |
| 208 | + top_p = kwargs.get("top_p") |
| 209 | + if top_p is not None: |
| 210 | + set_data_normalized(span, SPANDATA.GEN_AI_REQUEST_TOP_P, top_p) |
| 211 | + |
186 | 212 | res = yield f, args, kwargs |
187 | 213 |
|
188 | 214 | with capture_internal_exceptions(): |
189 | 215 | if should_send_default_pii() and integration.include_prompts: |
190 | 216 | set_data_normalized(span, SPANDATA.GEN_AI_REQUEST_MESSAGES, messages) |
191 | 217 |
|
192 | | - set_data_normalized(span, SPANDATA.GEN_AI_SYSTEM, "openai") |
193 | | - set_data_normalized(span, SPANDATA.GEN_AI_REQUEST_MODEL, model) |
194 | | - set_data_normalized(span, SPANDATA.GEN_AI_OPERATION_NAME, "chat") |
195 | | - set_data_normalized(span, SPANDATA.AI_STREAMING, streaming) |
| 218 | + if hasattr(res, "model"): |
| 219 | + set_data_normalized(span, SPANDATA.GEN_AI_RESPONSE_MODEL, res.model) |
196 | 220 |
|
197 | 221 | if hasattr(res, "choices"): |
198 | 222 | if should_send_default_pii() and integration.include_prompts: |
199 | | - set_data_normalized( |
200 | | - span, |
201 | | - SPANDATA.GEN_AI_RESPONSE_TEXT, |
202 | | - list(map(lambda x: x.message, res.choices)), |
203 | | - ) |
| 223 | + response_text = [choice.message.dict() for choice in res.choices] |
| 224 | + if len(response_text) > 0: |
| 225 | + set_data_normalized( |
| 226 | + span, |
| 227 | + SPANDATA.GEN_AI_RESPONSE_TEXT, |
| 228 | + safe_serialize(response_text), |
| 229 | + ) |
| 230 | + |
204 | 231 | _calculate_token_usage(messages, res, span, None, integration.count_tokens) |
205 | 232 | span.__exit__(None, None, None) |
206 | 233 | elif hasattr(res, "_iterator"): |
|
0 commit comments