Module: Langfuse::TraceId

Defined in:
lib/langfuse/trace_id.rb

Overview

Deterministic and random trace/observation ID generation.

Mirrors the Python and JS SDK helpers so the same seed produces the same trace ID across all three SDKs. This lets callers correlate Langfuse traces with external system identifiers (database primary keys, request IDs, etc.) and score or reference traces later without having to persist the generated Langfuse ID.

Examples:

Deterministic from an external ID

trace_id = Langfuse::TraceId.create(seed: "order-12345")
Langfuse.observe("process-order", trace_id: trace_id) { |span| ... }
Langfuse.create_score(name: "quality", value: 0.9, trace_id: trace_id)

Random (no seed)

trace_id = Langfuse::TraceId.create

Class Method Summary collapse

Class Method Details

.create(seed: nil) ⇒ String

Note:

Avoid passing PII, secrets, or credentials as seeds — the raw seed value appears in application code and may leak through logs/backtraces. Use stable external identifiers (database PKs, UUIDs, request IDs).

Generate a W3C trace ID (32 lowercase hex chars).

With no seed, delegates to OpenTelemetry’s random trace ID generator. With a seed, takes the first 16 bytes of SHA-256(seed) so the same input always produces the same trace ID.

Parameters:

  • seed (String, nil) (defaults to: nil)

    Optional seed for deterministic generation. Must be a String if provided; non-String values raise ArgumentError for cross-SDK parity (Python/JS both reject non-strings).

Returns:

  • (String)

    32-character lowercase hex trace ID

Raises:

  • (ArgumentError)

    if seed is not nil and not a String



42
43
44
45
46
# File 'lib/langfuse/trace_id.rb', line 42

def create(seed: nil)
  return OpenTelemetry::Trace.generate_trace_id.unpack1("H*") if seed.nil?

  Digest::SHA256.digest(validate_seed!(seed))[0, 16].unpack1("H*")
end