TsgcSSEParser

TsgcSSEParser is the text/event-stream interpreter used by TsgcSSEClient, and it can be used on its own. Feed it the raw bytes or the text of a stream in chunks of any size. Every complete event fires OnEvent and every valid retry: field fires OnRetry. It is useful to parse streaming responses of HTTP APIs that use the SSE format, for example the streamed answers of LLM providers, when the stream is read with another HTTP client. It is declared in the unit sgcHTTP_SSE_Client.

 

MemberDescription
procedure Feed(const aBytes: TBytes); overload;Parses a chunk of raw UTF-8 bytes. A chunk can end in the middle of a line or of an event, the rest is kept until the next call.
procedure Feed(const aText: string); overload;Parses a chunk of text.
procedure Reset;Discards the pending line and event, to start parsing a new stream.
property LastEventId: string;Last event id read from an id: field. It can be set to start with a known value.
property OnEvent: TsgcSSEEventEvent;Fires for every complete event with a TsgcSSEEvent.
property OnRetry: TsgcSSERetryEvent;Fires for every valid retry: field with the value in milliseconds. TsgcSSERetryEvent = procedure(Sender: TObject; aRetry: Integer) of object.

 

Example


var
  oParser: TsgcSSEParser;
begin
oParser := TsgcSSEParser.Create;
Try
  oParser.OnEvent := OnParserEvent;
  oParser.OnRetry := OnParserRetry;
  // chunks can split a line or an event anywhere
  oParser.Feed('event: delta'#10'data: {"text":"Hel');
  oParser.Feed('lo"}'#10#10);
  oParser.Feed(TEncoding.UTF8.GetBytes('id: 7'#10'data: done'#10#10));
  ShowMessage('last id: ' + oParser.LastEventId);
  // start again for a new response
  oParser.Reset;
Finally
  oParser.Free;
End;
end;

procedure TForm1.OnParserEvent(Sender: TObject; const aEvent: TsgcSSEEvent);
begin
  ShowMessage(aEvent.EventType + ' ' + aEvent.Id + ' ' + aEvent.Data);
end;

procedure TForm1.OnParserRetry(Sender: TObject; aRetry: Integer);
begin
  ShowMessage('server asks to retry after ' + IntToStr(aRetry) + ' ms');
end;