Class: Raif::StreamingResponses::Anthropic

Inherits:
Object
  • Object
show all
Defined in:
app/models/raif/streaming_responses/anthropic.rb

Instance Method Summary collapse

Constructor Details

#initializeAnthropic

Returns a new instance of Anthropic.



5
6
7
8
# File 'app/models/raif/streaming_responses/anthropic.rb', line 5

def initialize
  @response_json = { "content" => [], "usage" => {} }
  @finish_reason = nil
end

Instance Method Details

#current_response_jsonObject



58
59
60
61
# File 'app/models/raif/streaming_responses/anthropic.rb', line 58

def current_response_json
  @response_json["stop_reason"] = @finish_reason
  @response_json
end

#process_streaming_event(event_type, event) ⇒ 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
# File 'app/models/raif/streaming_responses/anthropic.rb', line 10

def process_streaming_event(event_type, event)
  delta = nil
  index = event["index"]

  case event_type
  when "message_start"
    @response_json = event["message"]
    @response_json["content"] = []
    @response_json["usage"] ||= {}
  when "content_block_start"
    @response_json["content"][index] = event["content_block"]
    if event.dig("content_block", "type") == "tool_use"
      @response_json["content"][index]["input"] = ""
    end
  when "content_block_delta"
    delta_chunk = event["delta"]
    if delta_chunk["type"] == "text_delta"
      delta = delta_chunk["text"]
      @response_json["content"][index]["text"] += delta if delta
    elsif delta_chunk["type"] == "input_json_delta"
      @response_json["content"][index]["input"] += delta_chunk["partial_json"]
    end
  when "content_block_stop"
    content_block = @response_json["content"][index]
    if content_block&.dig("type") == "tool_use"
      begin
        content_block["input"] = JSON.parse(content_block["input"])
      rescue JSON::ParserError
        # If parsing fails, leave as a string
      end
    end
  when "message_delta"
    @finish_reason = event.dig("delta", "stop_reason")
    @response_json["usage"]["output_tokens"] = event.dig("usage", "output_tokens")
  when "message_stop"
    @finish_reason = "stop"
  when "error"
    error_details = event["error"]
    raise Raif::Errors::StreamingError.new(
      message: error_details["message"],
      type: error_details["type"],
      event: event
    )
  end

  [delta, @finish_reason]
end