Class: AgUiProtocol::Encoder::EventEncoder

Inherits:
Object
  • Object
show all
Extended by:
T::Sig
Defined in:
lib/ag_ui_protocol/encoder/event_encoder.rb

Overview

The ‘EventEncoder` class is responsible for encoding `BaseEvent` objects into string representations that can be transmitted to clients.

“‘ruby

require “ag_ui_protocol”

encoder = AgUiProtocol::EventEncoder.new

event = AgUiProtocol::Core::Events::TextMessageContentEvent.new(

message_id: "msg_123",
delta: "Hello, world!"

)

encoded = encoder.encode(event)

“‘

### Usage

The ‘EventEncoder` is typically used in HTTP handlers to convert event objects into a stream of data. The current implementation encodes events as Server-Sent Events (SSE), which can be consumed by clients using the EventSource API.

### Implementation Details

Internally, the encoder converts events to JSON and formats them as Server-Sent Events with the following structure (each event terminated by two literal newline characters, shown here as escape sequences):

data: {json-serialized event}\n\n

This format allows clients to receive a continuous stream of events and process them as they arrive.

Instance Method Summary collapse

Constructor Details

#initialize(accept: nil) ⇒ EventEncoder

Returns a new instance of EventEncoder.



58
59
60
# File 'lib/ag_ui_protocol/encoder/event_encoder.rb', line 58

def initialize(accept: nil)
  @accept = accept
end

Instance Method Details

#content_typeObject



66
67
68
# File 'lib/ag_ui_protocol/encoder/event_encoder.rb', line 66

def content_type
  @accept || "text/event-stream"
end

#encode(event) ⇒ Object



75
76
77
78
79
# File 'lib/ag_ui_protocol/encoder/event_encoder.rb', line 75

def encode(event)
  payload = event.as_json

  "data: #{JSON.generate(payload)}\n\n"
end