Class: LittleGhost::Providers::Anthropic::Normalizer

Inherits:
Object
  • Object
show all
Defined in:
lib/little_ghost/providers/anthropic.rb

Overview

:nodoc:

Instance Method Summary collapse

Constructor Details

#initialize(model:) ⇒ Normalizer

Returns a new instance of Normalizer.



110
111
112
113
114
115
116
117
# File 'lib/little_ghost/providers/anthropic.rb', line 110

def initialize(model:)
  @model = model
  @text = +""
  @reasoning = +""
  @tools = {}
  @usage = Usage.new
  @terminal = false
end

Instance Method Details

#consume(event) ⇒ Object



119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
# File 'lib/little_ghost/providers/anthropic.rb', line 119

def consume(event)
  case event["type"]
  when "message_start"
    message = event.fetch("message")
    @id = message["id"]
    @usage = usage(message["usage"])
    [StreamEvent.build(:message_start, id: @id, model: message["model"] || @model)]
  when "content_block_start"
    start_block(event)
  when "content_block_delta"
    delta_block(event)
  when "content_block_stop"
    stop_block(event)
  when "message_delta"
    @stop_reason = stop_reason(event.dig("delta", "stop_reason"))
    @usage = usage(event["usage"], previous: @usage)
    [StreamEvent.build(:usage, usage: @usage)]
  when "message_stop"
    @terminal = true
    []
  when "error"
    raise ProviderError, "Anthropic request failed: #{event.dig("error", "message") || "unknown error"}"
  else
    []
  end
end

#finishObject

Raises:



146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
# File 'lib/little_ghost/providers/anthropic.rb', line 146

def finish
  raise ProtocolError, "Anthropic stream ended before message_stop" unless @terminal

  blocks = []
  blocks << Content::Reasoning.new(text: @reasoning) unless @reasoning.empty?
  blocks << Content::Text.new(text: @text) unless @text.empty?
  @tools.sort.each { |_index, tool| blocks << Content::ToolUse.new(id: tool[:id], name: tool[:name], input: parse_input(tool[:input])) }
  response = ModelResponse.new(
    message: Message.new(role: :assistant, content: blocks),
    stop_reason: @stop_reason || (@tools.empty? ? :end_turn : :tool_use),
    usage: @usage,
    metadata: {id: @id, model: @model}
  )
  [StreamEvent.build(:message_stop, response:)]
end