|
| 1 | +""" |
| 2 | +Copyright (c) 2024 Scale3 Labs |
| 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 | +""" |
| 16 | + |
| 17 | +import json |
| 18 | +from functools import wraps |
| 19 | + |
| 20 | +from langtrace.trace_attributes import ( |
| 21 | + LLMSpanAttributes, |
| 22 | + SpanAttributes, |
| 23 | +) |
| 24 | +from langtrace_python_sdk.utils import set_span_attribute |
| 25 | +from langtrace_python_sdk.utils.silently_fail import silently_fail |
| 26 | +from opentelemetry import trace |
| 27 | +from opentelemetry.trace import SpanKind |
| 28 | +from opentelemetry.trace.status import Status, StatusCode |
| 29 | +from opentelemetry.trace.propagation import set_span_in_context |
| 30 | +from langtrace_python_sdk.constants.instrumentation.common import ( |
| 31 | + SERVICE_PROVIDERS, |
| 32 | +) |
| 33 | +from langtrace_python_sdk.constants.instrumentation.aws_bedrock import APIS |
| 34 | +from langtrace_python_sdk.utils.llm import ( |
| 35 | + get_extra_attributes, |
| 36 | + get_langtrace_attributes, |
| 37 | + get_llm_request_attributes, |
| 38 | + get_llm_url, |
| 39 | + get_span_name, |
| 40 | + set_event_completion, |
| 41 | + set_span_attributes, |
| 42 | +) |
| 43 | + |
| 44 | + |
| 45 | +def traced_aws_bedrock_call(api_name: str, operation_name: str): |
| 46 | + def decorator(method_name: str, version: str, tracer): |
| 47 | + def wrapper(original_method): |
| 48 | + @wraps(original_method) |
| 49 | + def wrapped_method(*args, **kwargs): |
| 50 | + service_provider = SERVICE_PROVIDERS["AWS_BEDROCK"] |
| 51 | + |
| 52 | + input_content = [ |
| 53 | + { |
| 54 | + 'role': message.get('role', 'user'), |
| 55 | + 'content': message.get('content', [])[0].get('text', "") |
| 56 | + } |
| 57 | + for message in kwargs.get('messages', []) |
| 58 | + ] |
| 59 | + |
| 60 | + span_attributes = { |
| 61 | + **get_langtrace_attributes(version, service_provider, vendor_type="framework"), |
| 62 | + **get_llm_request_attributes(kwargs, operation_name=operation_name, prompts=input_content), |
| 63 | + **get_llm_url(args[0] if args else None), |
| 64 | + SpanAttributes.LLM_PATH: APIS[api_name]["ENDPOINT"], |
| 65 | + **get_extra_attributes(), |
| 66 | + } |
| 67 | + |
| 68 | + if api_name == "CONVERSE": |
| 69 | + span_attributes.update({ |
| 70 | + SpanAttributes.LLM_REQUEST_MODEL: kwargs.get('modelId'), |
| 71 | + SpanAttributes.LLM_REQUEST_MAX_TOKENS: kwargs.get('inferenceConfig', {}).get('maxTokens'), |
| 72 | + SpanAttributes.LLM_REQUEST_TEMPERATURE: kwargs.get('inferenceConfig', {}).get('temperature'), |
| 73 | + SpanAttributes.LLM_REQUEST_TOP_P: kwargs.get('inferenceConfig', {}).get('top_p'), |
| 74 | + }) |
| 75 | + |
| 76 | + attributes = LLMSpanAttributes(**span_attributes) |
| 77 | + |
| 78 | + with tracer.start_as_current_span( |
| 79 | + name=get_span_name(APIS[api_name]["METHOD"]), |
| 80 | + kind=SpanKind.CLIENT, |
| 81 | + context=set_span_in_context(trace.get_current_span()), |
| 82 | + ) as span: |
| 83 | + set_span_attributes(span, attributes) |
| 84 | + try: |
| 85 | + result = original_method(*args, **kwargs) |
| 86 | + _set_response_attributes(span, kwargs, result) |
| 87 | + span.set_status(StatusCode.OK) |
| 88 | + return result |
| 89 | + except Exception as err: |
| 90 | + span.record_exception(err) |
| 91 | + span.set_status(Status(StatusCode.ERROR, str(err))) |
| 92 | + raise err |
| 93 | + |
| 94 | + return wrapped_method |
| 95 | + return wrapper |
| 96 | + return decorator |
| 97 | + |
| 98 | + |
| 99 | +converse = traced_aws_bedrock_call("CONVERSE", "converse") |
| 100 | + |
| 101 | + |
| 102 | +def converse_stream(original_method, version, tracer): |
| 103 | + def traced_method(wrapped, instance, args, kwargs): |
| 104 | + service_provider = SERVICE_PROVIDERS["AWS_BEDROCK"] |
| 105 | + |
| 106 | + span_attributes = { |
| 107 | + **get_langtrace_attributes |
| 108 | + (version, service_provider, vendor_type="llm"), |
| 109 | + **get_llm_request_attributes(kwargs), |
| 110 | + **get_llm_url(instance), |
| 111 | + SpanAttributes.LLM_PATH: APIS["CONVERSE_STREAM"]["ENDPOINT"], |
| 112 | + **get_extra_attributes(), |
| 113 | + } |
| 114 | + |
| 115 | + attributes = LLMSpanAttributes(**span_attributes) |
| 116 | + |
| 117 | + with tracer.start_as_current_span( |
| 118 | + name=get_span_name(APIS["CONVERSE_STREAM"]["METHOD"]), |
| 119 | + kind=SpanKind.CLIENT, |
| 120 | + context=set_span_in_context(trace.get_current_span()), |
| 121 | + ) as span: |
| 122 | + set_span_attributes(span, attributes) |
| 123 | + try: |
| 124 | + result = wrapped(*args, **kwargs) |
| 125 | + _set_response_attributes(span, kwargs, result) |
| 126 | + span.set_status(StatusCode.OK) |
| 127 | + return result |
| 128 | + except Exception as err: |
| 129 | + span.record_exception(err) |
| 130 | + span.set_status(Status(StatusCode.ERROR, str(err))) |
| 131 | + raise err |
| 132 | + |
| 133 | + return traced_method |
| 134 | + |
| 135 | + |
| 136 | +@silently_fail |
| 137 | +def _set_response_attributes(span, kwargs, result): |
| 138 | + set_span_attribute(span, SpanAttributes.LLM_RESPONSE_MODEL, kwargs.get('modelId')) |
| 139 | + set_span_attribute(span, SpanAttributes.LLM_TOP_K, kwargs.get('additionalModelRequestFields', {}).get('top_k')) |
| 140 | + content = result.get('output', {}).get('message', {}).get('content', []) |
| 141 | + if len(content) > 0: |
| 142 | + role = result.get('output', {}).get('message', {}).get('role', "assistant") |
| 143 | + responses = [ |
| 144 | + {"role": role, "content": c.get('text', "")} |
| 145 | + for c in content |
| 146 | + ] |
| 147 | + set_event_completion(span, responses) |
| 148 | + |
| 149 | + if 'usage' in result: |
| 150 | + set_span_attributes( |
| 151 | + span, |
| 152 | + { |
| 153 | + SpanAttributes.LLM_USAGE_COMPLETION_TOKENS: result['usage'].get('outputTokens'), |
| 154 | + SpanAttributes.LLM_USAGE_PROMPT_TOKENS: result['usage'].get('inputTokens'), |
| 155 | + SpanAttributes.LLM_USAGE_TOTAL_TOKENS: result['usage'].get('totalTokens'), |
| 156 | + } |
| 157 | + ) |
0 commit comments