-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsse.go
More file actions
230 lines (196 loc) · 4.72 KB
/
sse.go
File metadata and controls
230 lines (196 loc) · 4.72 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
package iteragent
import (
"bufio"
"bytes"
"context"
"encoding/json"
"fmt"
"io"
"net/http"
"strings"
"sync"
)
type SSEEvent struct {
Event string
Data string
}
type SSEClient struct {
client *http.Client
}
func NewSSEClient() *SSEClient {
return &SSEClient{
client: &http.Client{},
}
}
func (c *SSEClient) Stream(ctx context.Context, url string, headers map[string]string, body []byte, onEvent func(SSEEvent)) error {
req, err := http.NewRequestWithContext(ctx, "POST", url, bytes.NewReader(body))
if err != nil {
return err
}
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Accept", "text/event-stream")
for k, v := range headers {
req.Header.Set(k, v)
}
resp, err := c.client.Do(req)
if err != nil {
return err
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
body, _ := io.ReadAll(resp.Body)
return fmt.Errorf("SSE request failed (%d): %s", resp.StatusCode, string(body))
}
reader := bufio.NewReader(resp.Body)
var event string
var data strings.Builder
for {
line, err := reader.ReadString('\n')
if err == io.EOF {
break
}
if err != nil {
break
}
line = strings.TrimRight(line, "\r\n")
if strings.HasPrefix(line, "event:") {
event = strings.TrimSpace(strings.TrimPrefix(line, "event:"))
continue
}
if strings.HasPrefix(line, "data:") {
data.WriteString(strings.TrimSpace(strings.TrimPrefix(line, "data:")))
data.WriteString("\n")
continue
}
if line == "" && data.Len() > 0 {
onEvent(SSEEvent{
Event: event,
Data: strings.TrimSpace(data.String()),
})
event = ""
data.Reset()
}
}
return nil
}
type SSEResponse struct {
mu sync.Mutex
content strings.Builder
messages []Message
stopped bool
}
func NewSSEResponse() *SSEResponse {
return &SSEResponse{
messages: []Message{},
}
}
func (r *SSEResponse) AddContent(content string) {
r.mu.Lock()
defer r.mu.Unlock()
r.content.WriteString(content)
}
func (r *SSEResponse) GetContent() string {
r.mu.Lock()
defer r.mu.Unlock()
return r.content.String()
}
func (r *SSEResponse) AddMessage(msg Message) {
r.mu.Lock()
defer r.mu.Unlock()
r.messages = append(r.messages, msg)
}
func (r *SSEResponse) GetMessages() []Message {
r.mu.Lock()
defer r.mu.Unlock()
return r.messages
}
func (r *SSEResponse) Stop() {
r.mu.Lock()
defer r.mu.Unlock()
r.stopped = true
}
func (r *SSEResponse) IsStopped() bool {
r.mu.Lock()
defer r.mu.Unlock()
return r.stopped
}
// ParseAnthropicSSE extracts the incremental text token from an Anthropic
// streaming SSE data payload. Returns ("", false) for non-text events.
//
// Anthropic SSE format for text tokens:
//
// {"type":"content_block_delta","index":0,"delta":{"type":"text_delta","text":"Hello"}}
func ParseAnthropicSSE(data string) (string, bool) {
var event struct {
Type string `json:"type"`
Delta struct {
Type string `json:"type"`
Text string `json:"text"`
} `json:"delta"`
}
if err := json.Unmarshal([]byte(data), &event); err != nil {
return "", false
}
if event.Type == "content_block_delta" && event.Delta.Type == "text_delta" && event.Delta.Text != "" {
return event.Delta.Text, true
}
return "", false
}
func ParseOpenAISSE(data string) (string, bool) {
var event struct {
Choices []struct {
Delta struct {
Content string `json:"content"`
} `json:"delta"`
} `json:"choices"`
}
if err := json.Unmarshal([]byte(data), &event); err != nil {
return "", false
}
if len(event.Choices) > 0 && event.Choices[0].Delta.Content != "" {
return event.Choices[0].Delta.Content, true
}
return "", false
}
// ParseOpenAIResponsesSSE extracts text tokens from the OpenAI Responses API SSE stream.
//
// Responses API streaming event format:
//
// event: response.content_part.delta
// data: {"type":"response.content_part.delta","delta":{"type":"text","text":"Hello"}}
func ParseOpenAIResponsesSSE(e SSEEvent) (string, bool) {
if e.Event != "response.content_part.delta" {
return "", false
}
var payload struct {
Delta struct {
Type string `json:"type"`
Text string `json:"text"`
} `json:"delta"`
}
if err := json.Unmarshal([]byte(e.Data), &payload); err != nil {
return "", false
}
if payload.Delta.Type == "text" && payload.Delta.Text != "" {
return payload.Delta.Text, true
}
return "", false
}
func ParseGeminiSSE(data string) (string, bool) {
var event struct {
Candidates []struct {
Content struct {
Parts []struct {
Text string `json:"text"`
} `json:"parts"`
} `json:"content"`
} `json:"candidates"`
}
if err := json.Unmarshal([]byte(data), &event); err != nil {
return "", false
}
if len(event.Candidates) > 0 && len(event.Candidates[0].Content.Parts) > 0 {
return event.Candidates[0].Content.Parts[0].Text, true
}
return "", false
}