Class: Braintrust::Contrib::OpenAI::ChatPatcher
- 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
- .applicable? ⇒ Boolean
- .patch_stream_classes ⇒ Object
- .patched?(**options) ⇒ Boolean
-
.perform_patch(**options) ⇒ void
Perform the actual patching.
Methods inherited from Patcher
Class Method Details
.applicable? ⇒ Boolean
15 16 17 |
# File 'lib/braintrust/contrib/openai/patcher.rb', line 15 def applicable? defined?(::OpenAI::Client) end |
.patch_stream_classes ⇒ Object
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
19 20 21 22 23 24 |
# File 'lib/braintrust/contrib/openai/patcher.rb', line 19 def patched?(**) # Use the target's singleton class if provided, otherwise check the base class. target_class = get_singleton_class([: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.
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(**) 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 [:target] # Instance-level (for only this client) raise ArgumentError, "target must be a kind of ::OpenAI::Client" unless [:target].is_a?(::OpenAI::Client) get_singleton_class([:target]).include(Instrumentation::Chat::Completions) else # Class-level (for all clients) ::OpenAI::Resources::Chat::Completions.include(Instrumentation::Chat::Completions) end end |