|
| 1 | + |
| 2 | +# Copyright 2010 New Relic, Inc. |
| 3 | +# |
| 4 | +# Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | +# you may not use this file except in compliance with the License. |
| 6 | +# You may obtain a copy of the License at |
| 7 | +# |
| 8 | +# http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | +# |
| 10 | +# Unless required by applicable law or agreed to in writing, software |
| 11 | +# distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | +# See the License for the specific language governing permissions and |
| 14 | +# limitations under the License. |
| 15 | +import openai |
| 16 | +import uuid |
| 17 | +from newrelic.api.function_trace import FunctionTrace |
| 18 | +from newrelic.common.object_wrapper import wrap_function_wrapper |
| 19 | +from newrelic.api.transaction import current_transaction |
| 20 | +from newrelic.api.time_trace import get_trace_linking_metadata |
| 21 | +from newrelic.core.config import global_settings |
| 22 | +from newrelic.common.object_names import callable_name |
| 23 | +from newrelic.core.attribute import MAX_LOG_MESSAGE_LENGTH |
| 24 | + |
| 25 | + |
| 26 | +def wrap_chat_completion_create(wrapped, instance, args, kwargs): |
| 27 | + transaction = current_transaction() |
| 28 | + |
| 29 | + if not transaction: |
| 30 | + return |
| 31 | + |
| 32 | + ft_name = callable_name(wrapped) |
| 33 | + with FunctionTrace(ft_name) as ft: |
| 34 | + response = wrapped(*args, **kwargs) |
| 35 | + |
| 36 | + if not response: |
| 37 | + return |
| 38 | + |
| 39 | + custom_attrs_dict = transaction._custom_params |
| 40 | + conversation_id = custom_attrs_dict.get("conversation_id", str(uuid.uuid4())) |
| 41 | + |
| 42 | + chat_completion_id = str(uuid.uuid4()) |
| 43 | + available_metadata = get_trace_linking_metadata() |
| 44 | + span_id = available_metadata.get("span.id", "") |
| 45 | + trace_id = available_metadata.get("trace.id", "") |
| 46 | + |
| 47 | + response_headers = getattr(response, "_nr_response_headers", None) |
| 48 | + response_model = response.model |
| 49 | + response_id = response.get("id", "") |
| 50 | + request_id = response_headers.get("x-request-id", "") |
| 51 | + settings = transaction.settings if transaction.settings is not None else global_settings() |
| 52 | + |
| 53 | + chat_completion_summary_dict = { |
| 54 | + "id": chat_completion_id, |
| 55 | + "appName": settings.app_name, |
| 56 | + "conversation_id": conversation_id, |
| 57 | + "span_id": span_id, |
| 58 | + "trace_id": trace_id, |
| 59 | + "transaction_id": transaction._transaction_id, |
| 60 | + "request_id": request_id, |
| 61 | + "api_key_last_four_digits": f"sk-{response.api_key[-4:]}", |
| 62 | + "duration": ft.duration, |
| 63 | + "request.model": kwargs.get("model") or kwargs.get("engine"), |
| 64 | + "response.model": response_model, |
| 65 | + "response.organization": response.organization, |
| 66 | + "response.usage.completion_tokens": response.usage.completion_tokens, |
| 67 | + "response.usage.total_tokens": response.usage.total_tokens, |
| 68 | + "response.usage.prompt_tokens": response.usage.prompt_tokens, |
| 69 | + "request.temperature": kwargs.get("temperature", ""), |
| 70 | + "request.max_tokens": kwargs.get("max_tokens", ""), |
| 71 | + "response.choices.finish_reason": response.choices[0].finish_reason, |
| 72 | + "response.api_type": response.api_type, |
| 73 | + "response.headers.llmVersion": response_headers.get("openai-version", ""), |
| 74 | + "response.headers.ratelimitLimitRequests": check_rate_limit_header(response_headers, "x-ratelimit-limit-requests", True), |
| 75 | + "response.headers.ratelimitLimitTokens": check_rate_limit_header(response_headers, "x-ratelimit-limit-tokens", True), |
| 76 | + "response.headers.ratelimitResetTokens": check_rate_limit_header(response_headers, "x-ratelimit-reset-tokens", False), |
| 77 | + "response.headers.ratelimitResetRequests": check_rate_limit_header(response_headers, "x-ratelimit-reset-requests", False), |
| 78 | + "response.headers.ratelimitRemainingTokens": check_rate_limit_header(response_headers, "x-ratelimit-remaining-tokens", True), |
| 79 | + "response.headers.ratelimitRemainingRequests": check_rate_limit_header(response_headers, "x-ratelimit-remaining-requests", True), |
| 80 | + "vendor": "openAI", |
| 81 | + "ingest_source": "Python", |
| 82 | + "number_of_messages": len(kwargs.get("messages", [])) + len(response.choices), |
| 83 | + } |
| 84 | + |
| 85 | + transaction.record_ml_event("LlmChatCompletionSummary", chat_completion_summary_dict) |
| 86 | + message_list = list(kwargs.get("messages", [])) + [response.choices[0].message] |
| 87 | + |
| 88 | + create_chat_completion_message_event(transaction, settings.app_name, message_list, chat_completion_id, span_id, trace_id, response_model, response_id, request_id) |
| 89 | + |
| 90 | + return response |
| 91 | + |
| 92 | + |
| 93 | +def check_rate_limit_header(response_headers, header_name, is_int): |
| 94 | + if not response_headers: |
| 95 | + return "" |
| 96 | + |
| 97 | + if header_name in response_headers: |
| 98 | + header_value = response_headers.get(header_name) |
| 99 | + if is_int: |
| 100 | + header_value = int(header_value) |
| 101 | + return header_value |
| 102 | + else: |
| 103 | + return "" |
| 104 | + |
| 105 | + |
| 106 | +def create_chat_completion_message_event(transaction, app_name, message_list, chat_completion_id, span_id, trace_id, response_model, response_id, request_id): |
| 107 | + if not transaction: |
| 108 | + return |
| 109 | + |
| 110 | + for index, message in enumerate(message_list): |
| 111 | + chat_completion_message_dict = { |
| 112 | + "id": "%s-%s" % (response_id, index), |
| 113 | + "appName": app_name, |
| 114 | + "request_id": request_id, |
| 115 | + "span_id": span_id, |
| 116 | + "trace_id": trace_id, |
| 117 | + "transaction_id": transaction._transaction_id, |
| 118 | + "content": message.get("content", "")[:MAX_LOG_MESSAGE_LENGTH], |
| 119 | + "role": message.get("role"), |
| 120 | + "completion_id": chat_completion_id, |
| 121 | + "sequence": index, |
| 122 | + "response.model": response_model, |
| 123 | + "vendor": "openAI", |
| 124 | + "ingest_source": "Python", |
| 125 | + } |
| 126 | + transaction.record_ml_event("LlmChatCompletionMessage", chat_completion_message_dict) |
| 127 | + |
| 128 | + |
| 129 | +def wrap_convert_to_openai_object(wrapped, instance, args, kwargs): |
| 130 | + resp = args[0] |
| 131 | + returned_response = wrapped(*args, **kwargs) |
| 132 | + |
| 133 | + if isinstance(resp, openai.openai_response.OpenAIResponse): |
| 134 | + setattr(returned_response, "_nr_response_headers", getattr(resp, "_headers", {})) |
| 135 | + |
| 136 | + return returned_response |
| 137 | + |
| 138 | + |
| 139 | +def instrument_openai_api_resources_chat_completion(module): |
| 140 | + if hasattr(module.ChatCompletion, "create"): |
| 141 | + wrap_function_wrapper(module, "ChatCompletion.create", wrap_chat_completion_create) |
| 142 | + |
| 143 | + |
| 144 | +def instrument_openai_util(module): |
| 145 | + wrap_function_wrapper(module, "convert_to_openai_object", wrap_convert_to_openai_object) |
0 commit comments