Class: LangfuseContext

Inherits:
Object
  • Object
show all
Extended by:
T::Sig
Defined in:
lib/langfuse_context.rb

Constant Summary collapse

ContextHash =

Define the type for the context hash

T.type_alias { T::Hash[Symbol, T.nilable(String)] }

Class Method Summary collapse

Class Method Details

.currentObject



13
14
15
16
17
18
19
20
# File 'lib/langfuse_context.rb', line 13

def self.current
  # T.let is used for type assertion
  context = T.let(Thread.current[:langfuse_context], T.nilable(ContextHash))
  # Initialize if nil
  context ||= T.let({}, ContextHash)
  Thread.current[:langfuse_context] = context
  context
end

.current_span_idObject



30
31
32
# File 'lib/langfuse_context.rb', line 30

def self.current_span_id
  current[:span_id]
end

.current_trace_idObject



24
25
26
# File 'lib/langfuse_context.rb', line 24

def self.current_trace_id
  current[:trace_id]
end

.with_span(span, &_block) ⇒ Object



60
61
62
63
64
65
66
67
68
69
70
71
72
# File 'lib/langfuse_context.rb', line 60

def self.with_span(span, &_block)
  old_context = current.dup
  begin
    # Assuming span.id returns a String
    span_id = T.let(T.unsafe(span).id, T.nilable(String))
    # Merge span_id into the current context
    new_context = current.merge({ span_id: span_id })
    Thread.current[:langfuse_context] = new_context if span_id
    yield
  ensure
    Thread.current[:langfuse_context] = old_context
  end
end

.with_trace(trace, &_block) ⇒ Object



41
42
43
44
45
46
47
48
49
50
51
# File 'lib/langfuse_context.rb', line 41

def self.with_trace(trace, &_block)
  old_context = current.dup
  begin
    # Assuming trace.id returns a String
    trace_id = T.let(T.unsafe(trace).id, T.nilable(String))
    Thread.current[:langfuse_context] = { trace_id: trace_id } if trace_id
    yield
  ensure
    Thread.current[:langfuse_context] = old_context
  end
end