Class: Braintrust::Contrib::OpenAI::ChatPatcher

Inherits:
Patcher
  • Object
show all
Defined in:
lib/braintrust/contrib/openai/patcher.rb

Overview

Patcher for OpenAI integration - implements class-level patching. All new OpenAI::Client instances created after patch! will be automatically instrumented.

Class Method Summary collapse

Methods inherited from Patcher

inherited, patch!, reset!

Class Method Details

.applicable?Boolean

Returns:

  • (Boolean)


15
16
17
# File 'lib/braintrust/contrib/openai/patcher.rb', line 15

def applicable?
  defined?(::OpenAI::Client)
end

.patch_stream_classesObject



50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
# File 'lib/braintrust/contrib/openai/patcher.rb', line 50

def patch_stream_classes
  # Patch ChatCompletionStream for stream() method
  if defined?(::OpenAI::Helpers::Streaming::ChatCompletionStream)
    unless Instrumentation::Chat::ChatCompletionStream.applied?(::OpenAI::Helpers::Streaming::ChatCompletionStream)
      ::OpenAI::Helpers::Streaming::ChatCompletionStream.include(Instrumentation::Chat::ChatCompletionStream)
    end
  end

  # Patch Internal::Stream for stream_raw() method
  if defined?(::OpenAI::Internal::Stream)
    unless Instrumentation::Chat::InternalStream.applied?(::OpenAI::Internal::Stream)
      ::OpenAI::Internal::Stream.include(Instrumentation::Chat::InternalStream)
    end
  end
end

.patched?(**options) ⇒ Boolean

Returns:

  • (Boolean)


19
20
21
22
23
24
# File 'lib/braintrust/contrib/openai/patcher.rb', line 19

def patched?(**options)
  # Use the target's singleton class if provided, otherwise check the base class.
  target_class = get_singleton_class(options[:target]) || ::OpenAI::Resources::Chat::Completions

  Instrumentation::Chat::Completions.applied?(target_class)
end

.perform_patch(**options) ⇒ void

This method returns an undefined value.

Perform the actual patching.

Parameters:

  • options (Hash)

    Configuration options passed from integration

Options Hash (**options):

  • :target (Object)

    Optional target instance to patch

  • :tracer_provider (OpenTelemetry::SDK::Trace::TracerProvider)

    Optional tracer provider



31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
# File 'lib/braintrust/contrib/openai/patcher.rb', line 31

def perform_patch(**options)
  return unless applicable?

  # Stream classes are shared across all clients, patch at class level.
  # The instrumentation short-circuits when no context is present,
  # so uninstrumented clients' streams pass through unaffected.
  patch_stream_classes

  if options[:target]
    # Instance-level (for only this client)
    raise ArgumentError, "target must be a kind of ::OpenAI::Client" unless options[:target].is_a?(::OpenAI::Client)

    get_singleton_class(options[:target]).include(Instrumentation::Chat::Completions)
  else
    # Class-level (for all clients)
    ::OpenAI::Resources::Chat::Completions.include(Instrumentation::Chat::Completions)
  end
end