Class: Anthropic::BetaRefusalFallbackMiddleware::BlockTracker

Inherits:
Object
  • Object
show all
Defined in:
lib/anthropic/helpers/refusal_fallback.rb

Overview

Block bookkeeping for one stream of the splice: accumulates each content block from its deltas (for the continuation prefill), shifts wire indices by index_base so they stay monotonic across hops, and tracks which blocks are still open so a refusal that cuts mid-block can close them.

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(index_base = 0) ⇒ BlockTracker

Returns a new instance of BlockTracker.

Parameters:

  • index_base (Integer) (defaults to: 0)


655
656
657
658
659
660
# File 'lib/anthropic/helpers/refusal_fallback.rb', line 655

def initialize(index_base = 0)
  @index_base = index_base
  @next_index = index_base
  @blocks = []
  @open = []
end

Instance Attribute Details

#next_indexInteger (readonly)

Returns one past the highest shifted block index seen.

Returns:

  • (Integer)

    one past the highest shifted block index seen



652
653
654
# File 'lib/anthropic/helpers/refusal_fallback.rb', line 652

def next_index
  @next_index
end

Instance Method Details

#close_open_blocks(y) ⇒ Object

Parameters:

  • y (Enumerator::Yielder)


687
688
689
690
691
692
693
694
695
696
697
# File 'lib/anthropic/helpers/refusal_fallback.rb', line 687

def close_open_blocks(y)
  @open.each do |index|
    y << "event: content_block_stop\ndata: #{JSON.generate(
      {
        type: 'content_block_stop',
        index: index
      }
    )}\n\n"
  end
  @open.clear
end

#content_blocksArray<Hash>

Returns the accumulated content blocks, in start order.

Returns:

  • (Array<Hash>)

    the accumulated content blocks, in start order



663
# File 'lib/anthropic/helpers/refusal_fallback.rb', line 663

def content_blocks = @blocks.map { _1[:block] }

#delta(event) ⇒ Object

Parameters:

  • event (Hash)


674
675
676
677
# File 'lib/anthropic/helpers/refusal_fallback.rb', line 674

def delta(event)
  apply_delta(event["index"], event["delta"])
  event["index"] += @index_base
end

#start(event) ⇒ Object

Parameters:

  • event (Hash)


666
667
668
669
670
671
# File 'lib/anthropic/helpers/refusal_fallback.rb', line 666

def start(event)
  @blocks << {index: event["index"], block: deep_dup(event["content_block"])}
  event["index"] += @index_base
  @open << event["index"]
  @next_index = [@next_index, event["index"] + 1].max
end

#stop(event) ⇒ Object

Parameters:

  • event (Hash)


680
681
682
683
684
# File 'lib/anthropic/helpers/refusal_fallback.rb', line 680

def stop(event)
  event["index"] += @index_base
  @open.delete(event["index"])
  @next_index = [@next_index, event["index"] + 1].max
end