session_id, request_id, model_id, and sampling_iteration
through async call chains via :mod:contextvars. Values automatically appear
in log records (via :class:MelleaContextFilter) and can be attached to
OpenTelemetry spans.
Example::
from mellea.telemetry.context import with_context, async_with_context, get_current_context
Synchronous (also works inside async functions):
with with_context(session_id=“s-1”, model_id=“granite”): result = backend.generate(…)Async-with syntax:
async with async_with_context(session_id=“s-1”, model_id=“granite”): result = await backend.generate(…)logs emitted here carry session_id and model_id automatically
Functions
FUNC get_session_id
None.
Returns:
- The active session ID string, or
Noneif not set.
FUNC get_request_id
None.
Returns:
- The active request ID string, or
Noneif not set.
FUNC get_model_id
None.
Returns:
- The active model ID string, or
Noneif not set.
FUNC get_sampling_iteration
None.
Returns:
- The current sampling iteration integer, or
Noneif not set.
FUNC get_current_context
None context values.
Returns:
- Mapping of field names to their current values, omitting keys whose
- value is
None.
FUNC generate_request_id
- A short hex string suitable for use as a
request_id.
FUNC with_context
asyncio.Task owns an isolated
copy of its ContextVar state).
Accepted keyword arguments: session_id, request_id, model_id,
sampling_iteration. Unknown keys raise :exc:ValueError.
Args:
**kwargs: Context fields to set within the block.
ValueError: If an unknown context field name is passed.
FUNC async_with_context
with_context.
Identical semantics but usable with async with syntax. Note that
:func:with_context also works inside async functions — use this
only when you specifically need async with syntax.
Args:
**kwargs: Context fields to set within the block.
ValueError: If an unknown context field name is passed.
Classes
CLASS MelleaContextFilter
Logging filter that injects telemetry context fields into every log record.
Fields from :func:get_current_context (session_id, request_id,
model_id, sampling_iteration) are copied onto each
:class:logging.LogRecord so they appear automatically in structured
JSON output produced by :class:~mellea.core.utils.JsonFormatter.
Methods:
FUNC filter
record: The log record being processed.
- Always
True— the record is never suppressed.