Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
29 changes: 25 additions & 4 deletions packages/ssestream/ssestream.go
Original file line number Diff line number Diff line change
Expand Up @@ -150,18 +150,39 @@ func (s *Stream[T]) Next() bool {
}

for s.decoder.Next() {
switch s.decoder.Event().Type {
eventType := s.decoder.Event().Type
eventData := s.decoder.Event().Data

// Check for [DONE] message which indicates end of stream
if string(eventData) == "[DONE]\n" || string(eventData) == "[DONE]" {
Copy link

Copilot AI Dec 18, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Converting byte slices to strings for comparison is inefficient. Use bytes.Equal() or bytes.HasPrefix() instead to avoid unnecessary allocations. For example: bytes.Equal(eventData, []byte("[DONE]")) or handle the newline separately.

Suggested change
if string(eventData) == "[DONE]\n" || string(eventData) == "[DONE]" {
if bytes.Equal(eventData, []byte("[DONE]\n")) || bytes.Equal(eventData, []byte("[DONE]")) {

Copilot uses AI. Check for mistakes.
// [DONE] indicates the end of the stream, so we return false
return false
}

// If event type is empty, try to infer from data or default to processing
if eventType == "" {
// For Anthropic's SSE format, data events without explicit type should still be processed
var nxt T
s.err = json.Unmarshal(eventData, &nxt)
if s.err != nil {
return false
}
s.cur = nxt
return true
}

switch eventType {
case "completion":
var nxt T
s.err = json.Unmarshal(s.decoder.Event().Data, &nxt)
s.err = json.Unmarshal(eventData, &nxt)
if s.err != nil {
return false
}
s.cur = nxt
return true
case "message_start", "message_delta", "message_stop", "content_block_start", "content_block_delta", "content_block_stop":
var nxt T
s.err = json.Unmarshal(s.decoder.Event().Data, &nxt)
s.err = json.Unmarshal(eventData, &nxt)
if s.err != nil {
return false
}
Expand All @@ -170,7 +191,7 @@ func (s *Stream[T]) Next() bool {
case "ping":
continue
case "error":
s.err = fmt.Errorf("received error while streaming: %s", string(s.decoder.Event().Data))
s.err = fmt.Errorf("received error while streaming: %s", string(eventData))
return false
}
}
Expand Down
Loading