Module: Tracekit::LLM::AnthropicInstrumentation

Defined in:
lib/tracekit/llm/anthropic_instrumentation.rb

Defined Under Namespace

Classes: AnthropicStreamAccumulator

Class Method Summary collapse

Class Method Details

.install(tracer) ⇒ Object



10
11
12
13
14
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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
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
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
# File 'lib/tracekit/llm/anthropic_instrumentation.rb', line 10

def install(tracer)
  begin
    require "anthropic"
  rescue LoadError
    # anthropic gem not available, check if it's already defined (e.g. in tests)
    return false unless defined?(::Anthropic::Client)
  end

  return false unless defined?(::Anthropic::Client)

  instrumentation_mod = Module.new do
    define_method(:messages) do |**params|
      # When called with no parameters, return the Messages::Client (for batches etc.)
      return super(**params) unless params[:parameters]

      parameters = params[:parameters]
      model = parameters[:model] || parameters["model"] || "unknown"
      stream_proc = parameters[:stream] || parameters["stream"]
      is_streaming = stream_proc.is_a?(Proc)
      capture = Common.capture_content?

      span = tracer.start_span("chat #{model}", kind: :client)

      begin
        Common.set_request_attributes(span,
          provider: "anthropic",
          model: model,
          max_tokens: parameters[:max_tokens] || parameters["max_tokens"],
          temperature: parameters[:temperature] || parameters["temperature"],
          top_p: parameters[:top_p] || parameters["top_p"]
        )

        # Capture input content
        if capture
          system_prompt = parameters[:system] || parameters["system"]
          Common.capture_system_instructions(span, system_prompt) if system_prompt
          messages = parameters[:messages] || parameters["messages"]
          Common.capture_input_messages(span, messages) if messages
        end

        if is_streaming
          # Wrap the user's stream proc to accumulate span data
          accumulator = AnthropicStreamAccumulator.new(span, capture)
          wrapper_proc = proc do |event|
            accumulator.process_event(event)
            stream_proc.call(event)
          end

          # Replace stream proc with our wrapper
          wrapped_params = parameters.merge(stream: wrapper_proc)
          result = super(parameters: wrapped_params)
          accumulator.finalize
          result
        else
          result = super(**params)
          handle_anthropic_response(span, result, capture)
          result
        end
      rescue => e
        Common.set_error_attributes(span, e)
        span.finish
        raise
      end
    end

    private

    def handle_anthropic_response(span, result, capture)
      # Anthropic response: { id, type, role, content, model, stop_reason, usage }
      content_blocks = result["content"] || result[:content] || []
      usage = result["usage"] || result[:usage] || {}

      Common.set_response_attributes(span,
        model: result["model"] || result[:model],
        id: result["id"] || result[:id],
        finish_reasons: [(result["stop_reason"] || result[:stop_reason])].compact,
        input_tokens: usage["input_tokens"] || usage[:input_tokens],
        output_tokens: usage["output_tokens"] || usage[:output_tokens]
      )

      # Cache tokens (Anthropic-specific)
      cache_creation = usage["cache_creation_input_tokens"] || usage[:cache_creation_input_tokens]
      cache_read = usage["cache_read_input_tokens"] || usage[:cache_read_input_tokens]
      span.set_attribute("gen_ai.usage.cache_creation.input_tokens", cache_creation) if cache_creation
      span.set_attribute("gen_ai.usage.cache_read.input_tokens", cache_read) if cache_read

      # Tool calls from content blocks
      content_blocks.each do |block|
        block_type = block["type"] || block[:type]
        if block_type == "tool_use"
          input_val = block["input"] || block[:input]
          args = input_val.is_a?(String) ? input_val : JSON.generate(input_val)
          Common.record_tool_call(span,
            name: block["name"] || block[:name] || "unknown",
            id: block["id"] || block[:id],
            arguments: args
          )
        end
      end

      # Output content capture
      if capture && content_blocks.any?
        Common.capture_output_messages(span, content_blocks)
      end
    rescue => _e
      # Never break user code
    ensure
      span.finish
    end
  end

  ::Anthropic::Client.prepend(instrumentation_mod)
  true
end