utils Module

Classes

DictWithLock

A wrapped dictionary with lock

Functions

as_utc_nano

as_utc_nano(dt: datetime) -> int

Parameters

Name Description
dt
Required

deprecated

Decorator to mark functions as deprecated.

deprecated(reason: str)

Parameters

Name Description
reason
Required

extract_context_from_headers

Extract an OpenTelemetry Context from W3C trace HTTP headers.

Parses traceparent (and optionally tracestate) headers and returns an OpenTelemetry Context that can be passed as parent_context to any scope's start() method.

extract_context_from_headers(headers: dict[str, str]) -> Context

Parameters

Name Description
headers
Required

Dictionary of HTTP headers containing trace context. Expected keys include traceparent and optionally tracestate.

Returns

Type Description

An OpenTelemetry Context containing the extracted trace information. If no valid trace context is found, returns an empty context.

extract_model_name

Extract model name from span names like:

  • 'chat.completions gpt-4o-mini' -> 'gpt-4o-mini'
  • 'chat.completions gpt-3.5-turbo' -> 'gpt-3.5-turbo'
  • 'chat.completions' -> None
extract_model_name(span_name: str) -> str | None

Parameters

Name Description
span_name
Required

flatten

flatten(*args: Any, **kwargs: Any) -> Iterator[tuple[str, Any]]

get_first_value

Returns the first non-null value corresponding to an input key, or None if no non-null value is found.

get_first_value(mapping: Mapping[KeyType, ValueType], keys: Iterable[KeyType]) -> ValueType | None

Parameters

Name Description
mapping
Required
keys
Required

get_sdk_version

Get the SDK version from package metadata.

get_sdk_version() -> str

Returns

Type Description

The SDK version string, or "0.0.0-unknown" if not found

get_traceparent

Return the W3C traceparent value from a headers dictionary.

get_traceparent(headers: dict[str, str]) -> str | None

Parameters

Name Description
headers
Required

Dictionary of HTTP headers, typically obtained from <xref:OpenTelemetryScope.inject_context_to_headers>.

Returns

Type Description

The traceparent string (e.g. "00-<trace-id>-<span-id>-<flags>"), or None if the key is not present.

record_exception

record_exception(span: Span, error: BaseException) -> None

Parameters

Name Description
span
Required
error
Required

safe_json_dumps

safe_json_dumps(obj: Any, **kwargs: Any) -> str

Parameters

Name Description
obj
Required

stop_on_exception

stop_on_exception(wrapped: Callable[[...], Iterator[tuple[str, Any]]]) -> Callable[[...], Iterator[tuple[str, Any]]]

Parameters

Name Description
wrapped
Required

validate_and_normalize_ip

Validate and normalize an IP address string.

Logs: Error message if the IP address is invalid

validate_and_normalize_ip(ip_string: str | None) -> str | None

Parameters

Name Description
ip_string
Required

The IP address string to validate (IPv4 or IPv6)

Returns

Type Description

The normalized IP address string if valid, None if invalid or None input