libs/core/langchain_core/utils/uuid.py PYTHON 58 lines View on github.com → Search inside
1"""UUID utility functions.23This module exports a uuid7 function to generate monotonic, time-ordered UUIDs4for tracing and similar operations.5"""67from __future__ import annotations89import typing10from uuid import UUID1112from uuid_utils.compat import uuid7 as _uuid_utils_uuid71314if typing.TYPE_CHECKING:15    from uuid import UUID1617_NANOS_PER_SECOND: typing.Final = 1_000_000_000181920def _to_timestamp_and_nanos(nanoseconds: int) -> tuple[int, int]:21    """Split a nanosecond timestamp into seconds and remaining nanoseconds."""22    seconds, nanos = divmod(nanoseconds, _NANOS_PER_SECOND)23    return seconds, nanos242526def uuid7(nanoseconds: int | None = None) -> UUID:27    """Generate a UUID from a Unix timestamp in nanoseconds and random bits.2829    UUIDv7 objects feature monotonicity within a millisecond.3031    Args:32        nanoseconds: Optional ns timestamp. If not provided, uses current time.3334    Returns:35        A UUIDv7 object.36    """37    # --- 48 ---   -- 4 --   --- 12 ---   -- 2 --   --- 30 ---   - 32 -38    # unix_ts_ms | version | counter_hi | variant | counter_lo | random39    #40    # 'counter = counter_hi | counter_lo' is a 42-bit counter constructed41    # with Method 1 of RFC 9562, §6.2, and its MSB is set to 0.42    #43    # 'random' is a 32-bit random value regenerated for every new UUID.44    #45    # If multiple UUIDs are generated within the same millisecond, the LSB46    # of 'counter' is incremented by 1. When overflowing, the timestamp is47    # advanced and the counter is reset to a random 42-bit integer with MSB48    # set to 0.4950    # For now, just delegate to the uuid_utils implementation51    if nanoseconds is None:52        return _uuid_utils_uuid7()53    seconds, nanos = _to_timestamp_and_nanos(nanoseconds)54    return _uuid_utils_uuid7(timestamp=seconds, nanos=nanos)555657__all__ = ["uuid7"]

Findings

✓ No findings reported for this file.

Get this view in your editor

Same data, no extra tab — call code_get_file + code_get_findings over MCP from Claude/Cursor/Copilot.