Class: DSPy::Context

Inherits:
Object
  • Object
show all
Defined in:
lib/dspy/context.rb

Class Method Summary collapse

Class Method Details

.clear!Object



62
63
64
# File 'lib/dspy/context.rb', line 62

def clear!
  Thread.current[:dspy_context] = nil
end

.currentObject



8
9
10
11
12
13
# File 'lib/dspy/context.rb', line 8

def current
  Thread.current[:dspy_context] ||= {
    trace_id: SecureRandom.uuid,
    span_stack: []
  }
end

.with_span(operation:, **attributes) ⇒ Object



15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
# File 'lib/dspy/context.rb', line 15

def with_span(operation:, **attributes)
  span_id = SecureRandom.uuid
  parent_span_id = current[:span_stack].last
  start_time = Process.clock_gettime(Process::CLOCK_MONOTONIC)
  
  # Prepare attributes with context information
  span_attributes = {
    trace_id: current[:trace_id],
    span_id: span_id,
    parent_span_id: parent_span_id,
    operation: operation,
    **attributes
  }
  
  # Log span start with proper hierarchy
  DSPy.log('span.start', **span_attributes)
  
  # Create OpenTelemetry span if observability is enabled
  otel_span = nil
  if DSPy::Observability.enabled?
    otel_span = DSPy::Observability.start_span(operation, span_attributes)
  end
  
  # Push to stack for child spans
  current[:span_stack].push(span_id)
  
  begin
    result = yield
  ensure
    # Pop from stack
    current[:span_stack].pop
    
    # Log span end with duration
    duration_ms = ((Process.clock_gettime(Process::CLOCK_MONOTONIC) - start_time) * 1000).round(2)
    DSPy.log('span.end',
      trace_id: current[:trace_id],
      span_id: span_id,
      duration_ms: duration_ms
    )
    
    # Finish OpenTelemetry span
    DSPy::Observability.finish_span(otel_span) if otel_span
  end
  
  result
end