@@ -82,6 +82,7 @@ def __init__(
8282 guardrail_words : Counter ,
8383 prompt_caching : Counter ,
8484 ):
85+ """Initialize the instrumentor and apply configuration settings."""
8586 self .vendor = ""
8687 self .model = ""
8788 self .is_stream = False
@@ -120,6 +121,7 @@ def _span_name(operation_name, model):
120121
121122
122123def is_metrics_enabled () -> bool :
124+ """Return True if metrics collection is enabled via environment variable."""
123125 return (os .getenv ("TRACELOOP_METRICS_ENABLED" ) or "true" ).lower () == "true"
124126
125127
@@ -132,7 +134,9 @@ def _with_tracer(
132134 event_logger ,
133135 to_wrap ,
134136 ):
137+ """Bind tracer and configuration parameters, returning the wrapped function factory."""
135138 def wrapper (wrapped , instance , args , kwargs ):
139+ """Invoke the instrumented function with bound tracer parameters."""
136140 return func (
137141 tracer ,
138142 metric_params ,
@@ -206,8 +210,10 @@ def _wrap(
206210
207211
208212def _instrumented_model_invoke (fn , tracer , metric_params , event_logger ):
213+ """Wrap invoke_model to create a span and record exceptions."""
209214 @wraps (fn )
210215 def with_instrumentation (* args , ** kwargs ):
216+ """Execute the wrapped AWS API call within an OTel span."""
211217 if context_api .get_value (SUPPRESS_LANGUAGE_MODEL_INSTRUMENTATION_KEY ):
212218 return fn (* args , ** kwargs )
213219
@@ -240,8 +246,10 @@ def with_instrumentation(*args, **kwargs):
240246def _instrumented_model_invoke_with_response_stream (
241247 fn , tracer , metric_params , event_logger
242248):
249+ """Wrap invoke_model_with_response_stream to create a span and record exceptions."""
243250 @wraps (fn )
244251 def with_instrumentation (* args , ** kwargs ):
252+ """Execute the wrapped AWS API call within an OTel span."""
245253 if context_api .get_value (SUPPRESS_LANGUAGE_MODEL_INSTRUMENTATION_KEY ):
246254 return fn (* args , ** kwargs )
247255
@@ -276,8 +284,10 @@ def _instrumented_converse(fn, tracer, metric_params, event_logger):
276284 # see
277285 # https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/bedrock-runtime/client/converse.html
278286 # for the request/response format
287+ """Wrap converse to create a span and record exceptions."""
279288 @wraps (fn )
280289 def with_instrumentation (* args , ** kwargs ):
290+ """Execute the wrapped AWS API call within an OTel span."""
281291 if context_api .get_value (SUPPRESS_LANGUAGE_MODEL_INSTRUMENTATION_KEY ):
282292 return fn (* args , ** kwargs )
283293
@@ -308,8 +318,10 @@ def with_instrumentation(*args, **kwargs):
308318
309319
310320def _instrumented_converse_stream (fn , tracer , metric_params , event_logger ):
321+ """Wrap converse_stream to create a span and record exceptions."""
311322 @wraps (fn )
312323 def with_instrumentation (* args , ** kwargs ):
324+ """Execute the wrapped AWS API call within an OTel span."""
313325 if context_api .get_value (SUPPRESS_LANGUAGE_MODEL_INSTRUMENTATION_KEY ):
314326 return fn (* args , ** kwargs )
315327
@@ -342,6 +354,7 @@ def with_instrumentation(*args, **kwargs):
342354@dont_throw
343355def _handle_stream_call (span , kwargs , response , metric_params , event_logger ):
344356
357+ """Attach a StreamingWrapper to the response body to finalize the span when streaming completes."""
345358 (provider , model_vendor , model ) = _get_vendor_model (kwargs .get ("modelId" ))
346359 request_body = json .loads (kwargs .get ("body" ))
347360
@@ -352,6 +365,7 @@ def _handle_stream_call(span, kwargs, response, metric_params, event_logger):
352365 @dont_throw
353366 def stream_done (response_body ):
354367
368+ """Finalize span attributes when the streaming response body is fully consumed."""
355369 metric_params .vendor = provider
356370 metric_params .model = model
357371 metric_params .is_stream = True
@@ -388,6 +402,7 @@ def stream_done(response_body):
388402
389403@dont_throw
390404def _handle_call (span : Span , kwargs , response , metric_params , event_logger ):
405+ """Read and record request/response attributes on the current span for a non-streaming call."""
391406 response ["body" ] = ReusableStreamingBody (
392407 response ["body" ]._raw_stream , response ["body" ]._content_length
393408 )
@@ -429,6 +444,7 @@ def _handle_call(span: Span, kwargs, response, metric_params, event_logger):
429444
430445@dont_throw
431446def _handle_converse (span , kwargs , response , metric_params , event_logger ):
447+ """Record converse request/response attributes on the current span."""
432448 (provider , model_vendor , model ) = _get_vendor_model (kwargs .get ("modelId" ))
433449 guardrail_converse (span , response , provider , model , metric_params )
434450
@@ -447,6 +463,7 @@ def _handle_converse(span, kwargs, response, metric_params, event_logger):
447463
448464@dont_throw
449465def _handle_converse_stream (span , kwargs , response , metric_params , event_logger ):
466+ """Attach streaming event handler to record converse_stream response attributes."""
450467 (provider , model_vendor , model ) = _get_vendor_model (kwargs .get ("modelId" ))
451468
452469 set_converse_model_span_attributes (span , provider , model , kwargs )
@@ -461,7 +478,9 @@ def _handle_converse_stream(span, kwargs, response, metric_params, event_logger)
461478 if stream :
462479
463480 def handler (func ):
481+ """Decorate the stream event parser to accumulate response content and record span attributes."""
464482 def wrap (* args , ** kwargs ):
483+ """Process each stream event, accumulate content, and record span attributes on completion."""
465484 response_msg = kwargs .pop ("response_msg" )
466485 tool_blocks = kwargs .pop ("tool_blocks" )
467486 reasoning_blocks = kwargs .pop ("reasoning_blocks" )
@@ -522,6 +541,7 @@ def wrap(*args, **kwargs):
522541def _get_vendor_model (modelId ):
523542 # Docs:
524543 # https://docs.aws.amazon.com/bedrock/latest/userguide/inference-profiles-support.html#inference-profiles-support-system
544+ """Parse modelId to extract provider, model vendor, and model name."""
525545 provider = GenAiSystemValues .AWS_BEDROCK .value
526546 model_vendor = "imported_model"
527547 model = modelId
@@ -540,6 +560,7 @@ def _get_vendor_model(modelId):
540560
541561
542562def _cross_region_check (value ):
563+ """Strip cross-region inference prefix from a model identifier string."""
543564 prefixes = ["us" , "us-gov" , "eu" , "apac" ]
544565 if any (value .startswith (prefix + "." ) for prefix in prefixes ):
545566 parts = value .split ("." )
@@ -580,6 +601,7 @@ class PromptCaching:
580601
581602
582603def _create_metrics (meter : Meter ):
604+ """Create and return OTel metric instruments for Bedrock token usage, duration, and guardrails."""
583605 token_histogram = meter .create_histogram (
584606 name = Meters .LLM_TOKEN_USAGE ,
585607 unit = "token" ,
@@ -679,15 +701,18 @@ def __init__(
679701 exception_logger = None ,
680702 use_legacy_attributes : bool = True ,
681703 ):
704+ """Initialize the instrumentor and apply configuration settings."""
682705 super ().__init__ ()
683706 Config .enrich_token_usage = enrich_token_usage
684707 Config .exception_logger = exception_logger
685708 Config .use_legacy_attributes = use_legacy_attributes
686709
687710 def instrumentation_dependencies (self ) -> Collection [str ]:
711+ """Return the package version constraints required by this instrumentor."""
688712 return _instruments
689713
690714 def _instrument (self , ** kwargs ):
715+ """Patch the target library to add OTel instrumentation."""
691716 tracer_provider = kwargs .get ("tracer_provider" )
692717 tracer = get_tracer (__name__ , __version__ , tracer_provider )
693718
@@ -764,6 +789,7 @@ def _instrument(self, **kwargs):
764789 )
765790
766791 def _uninstrument (self , ** kwargs ):
792+ """Remove OTel instrumentation patches from the target library."""
767793 for wrapped_method in WRAPPED_METHODS :
768794 wrap_package = wrapped_method .get ("package" )
769795 wrap_object = wrapped_method .get ("object" )
0 commit comments