Module: Braintrust::Contrib::Anthropic::Instrumentation::BetaMessages::InstanceMethods

Defined in:
lib/braintrust/contrib/anthropic/instrumentation/beta_messages.rb

Constant Summary collapse

METADATA_FIELDS =

Standard metadata fields (shared with stable API)

%i[
  model max_tokens temperature top_p top_k stop_sequences
  stream tools tool_choice thinking metadata service_tier
].freeze
BETA_METADATA_FIELDS =

Beta-specific metadata fields

%i[
  betas output_format
].freeze

Instance Method Summary collapse

Instance Method Details

#create(**params) ⇒ Object

Wrap synchronous beta.messages.create



40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
# File 'lib/braintrust/contrib/anthropic/instrumentation/beta_messages.rb', line 40

def create(**params)
  client = instance_variable_get(:@client)
  tracer = Braintrust::Contrib.tracer_for(client)

  tracer.in_span("anthropic.messages.create") do |span|
    # Pre-call instrumentation (swallow errors)
     = nil
    begin
       = (params)
      set_input(span, params)
    rescue => e
      Braintrust::Log.debug("Beta API: Failed to capture request: #{e.message}")
       ||= {"provider" => "anthropic", "api_version" => "beta"}
    end

    # API call - let errors propagate naturally
    response = nil
    time_to_first_token = Braintrust::Internal::Time.measure do
      response = super(**params)
    end

    # Post-call instrumentation (swallow errors)
    begin
      set_output(span, response)
      set_metrics(span, response, time_to_first_token)
      (span, , response)
    rescue => e
      Braintrust::Log.debug("Beta API: Failed to capture response: #{e.message}")
    end

    response
  end
end

#stream(**params) ⇒ Object

Wrap streaming beta.messages.stream Stores context on stream object for span creation during consumption



76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
# File 'lib/braintrust/contrib/anthropic/instrumentation/beta_messages.rb', line 76

def stream(**params)
  client = instance_variable_get(:@client)
  tracer = Braintrust::Contrib.tracer_for(client)

  # Pre-call instrumentation (swallow errors)
   = nil
  begin
     = (params, stream: true)
  rescue => e
    Braintrust::Log.debug("Beta API: Failed to build stream metadata: #{e.message}")
     = {"provider" => "anthropic", "api_version" => "beta", "stream" => true}
  end

  # API call - let errors propagate naturally
  stream_obj = super

  # Post-call instrumentation (swallow errors)
  begin
    Braintrust::Contrib::Context.set!(stream_obj,
      tracer: tracer,
      params: params,
      metadata: ,
      messages_instance: self,
      start_time: Braintrust::Internal::Time.measure)
  rescue => e
    Braintrust::Log.debug("Beta API: Failed to set stream context: #{e.message}")
  end

  stream_obj
end