Skip to main content
One id per message — read it inside any tool, log it on any hop, and grep your logs to follow a single request end to end. The user sends a message; the same correlation id appears in bot logs, agent tools, and delivery traces for end-to-end debugging.

Quick Start

1

Read the correlation id inside a tool

2

Wrap a turn with a known id

3

Include the id in every log line


How It Works

The id travels through Python’s contextvars — no thread-locals, no globals. Every async task or thread that inherits the context gets the same id automatically.

Configuration Options

Adopt-key precedence

When correlation_id_from(inbound) is called on a dict or object, it checks keys in order:

ID format

A freshly minted id is the first 8 hex characters of a uuid4: e.g. a3f1c9de. Short enough to type, unique enough for log correlation.

Public API

Import all helpers from the friendly path:

Common Patterns

Full turn with structured logging

Every log line carries correlation_id=tg-9182 — the tool, the session manager’s bot turn start debug line, and every other hop.

Forwarding an upstream id from a webhook

Passing through to downstream HTTP calls

Manual token management (advanced)

Prefer use_correlation_id(cid) as a context manager — it handles the reset automatically.

Best Practices

The id lives in a ContextVar. Reading it with current_correlation_id() is safe across async tasks and threads. Storing it in a module-level variable breaks concurrent request isolation.
Calling correlation_log_fields({"channel": "telegram"}) merges the current id into your extra dict in one call. This prevents typos like "correlaton_id" from silently breaking your log queries.
Downstream services can adopt the same id, extending your log trail across service boundaries without any shared state.
Calling set_correlation_id without a paired reset_correlation_id leaks the id into the parent context. Use with use_correlation_id(cid): — the reset happens automatically on block exit, even on exceptions.

The correlation_id is also the join key for spans emitted through Gateway Tracing Hook.

Gateway Metrics

Prometheus counters and gauges for every hop of the message flow.

Gateway Server

The gateway wires set_correlation_id on every turn automatically.