Class: LLM::EventStream::Event

Inherits:
Object
  • Object
show all
Defined in:
lib/llm/eventstream/event.rb

Constant Summary collapse

UNSET =
Object.new.freeze

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(chunk, field: UNSET, value: UNSET) ⇒ LLM::EventStream::Event

Parameters:

  • chunk (String)


37
38
39
40
41
42
# File 'lib/llm/eventstream/event.rb', line 37

def initialize(chunk, field: UNSET, value: UNSET)
  @field, @value = self.class.parse(chunk) if field.equal?(UNSET) || value.equal?(UNSET)
  @field = field unless field.equal?(UNSET)
  @value = value unless value.equal?(UNSET)
  @chunk = chunk
end

Instance Attribute Details

#chunkString (readonly)

Returns the full chunk

Returns:

  • (String)


32
33
34
# File 'lib/llm/eventstream/event.rb', line 32

def chunk
  @chunk
end

#fieldSymbol (readonly)

Returns the field name

Returns:

  • (Symbol)


22
23
24
# File 'lib/llm/eventstream/event.rb', line 22

def field
  @field
end

#valueString (readonly)

Returns the field value

Returns:

  • (String)


27
28
29
# File 'lib/llm/eventstream/event.rb', line 27

def value
  @value
end

Class Method Details

.parse(chunk) ⇒ Object



9
10
11
12
13
14
15
16
17
# File 'lib/llm/eventstream/event.rb', line 9

def self.parse(chunk)
  newline = chunk.end_with?("\n") ? chunk.bytesize - 1 : chunk.bytesize
  separator = chunk.index(":")
  return [nil, nil] unless separator
  field = chunk.byteslice(0, separator)
  value_start = separator + (chunk.getbyte(separator + 1) == 32 ? 2 : 1)
  value = value_start < newline ? chunk.byteslice(value_start, newline - value_start) : nil
  [field, value]
end

Instance Method Details

#data?Boolean

Returns true when the event represents a “data” chunk

Returns:

  • (Boolean)


54
55
56
# File 'lib/llm/eventstream/event.rb', line 54

def data?
  @field == "data"
end

#end?Boolean

Returns true when a chunk represents the end of the stream

Returns:

  • (Boolean)


75
76
77
# File 'lib/llm/eventstream/event.rb', line 75

def end?
  @value == "[DONE]"
end

#event?Boolean

Returns true when the event represents an “event” chunk

Returns:

  • (Boolean)


61
62
63
# File 'lib/llm/eventstream/event.rb', line 61

def event?
  @field == "event"
end

#id?Boolean

Returns true when the event represents an “id” chunk

Returns:

  • (Boolean)


47
48
49
# File 'lib/llm/eventstream/event.rb', line 47

def id?
  @field == "id"
end

#retry?Boolean

Returns true when the event represents a “retry” chunk

Returns:

  • (Boolean)


68
69
70
# File 'lib/llm/eventstream/event.rb', line 68

def retry?
  @field == "retry"
end