forked from zhouyangtingwen/dify-sdk-go
-
Notifications
You must be signed in to change notification settings - Fork 15
/
api_chat_stream.go
88 lines (77 loc) · 2.2 KB
/
api_chat_stream.go
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
package dify
import (
"bufio"
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"net/http"
)
type ChatMessageStreamResponse struct {
Event string `json:"event"`
TaskID string `json:"task_id"`
ID string `json:"id"`
Answer string `json:"answer"`
CreatedAt int64 `json:"created_at"`
ConversationID string `json:"conversation_id"`
}
type ChatMessageStreamChannelResponse struct {
ChatMessageStreamResponse
Err error `json:"-"`
}
func (api *API) ChatMessagesStreamRaw(ctx context.Context, req *ChatMessageRequest) (*http.Response, error) {
req.ResponseMode = "streaming"
httpReq, err := api.createBaseRequest(ctx, http.MethodPost, "/v1/chat-messages", req)
if err != nil {
return nil, err
}
return api.c.sendRequest(httpReq)
}
func (api *API) ChatMessagesStream(ctx context.Context, req *ChatMessageRequest) (chan ChatMessageStreamChannelResponse, error) {
httpResp, err := api.ChatMessagesStreamRaw(ctx, req)
if err != nil {
return nil, err
}
streamChannel := make(chan ChatMessageStreamChannelResponse)
go api.chatMessagesStreamHandle(ctx, httpResp, streamChannel)
return streamChannel, nil
}
func (api *API) chatMessagesStreamHandle(ctx context.Context, resp *http.Response, streamChannel chan ChatMessageStreamChannelResponse) {
defer resp.Body.Close()
defer close(streamChannel)
reader := bufio.NewReader(resp.Body)
for {
select {
case <-ctx.Done():
return
default:
line, err := reader.ReadBytes('\n')
if err != nil {
streamChannel <- ChatMessageStreamChannelResponse{
Err: fmt.Errorf("error reading line: %w", err),
}
return
}
if !bytes.HasPrefix(line, []byte("data:")) {
continue
}
line = bytes.TrimPrefix(line, []byte("data:"))
var resp ChatMessageStreamChannelResponse
if err = json.Unmarshal(line, &resp); err != nil {
streamChannel <- ChatMessageStreamChannelResponse{
Err: fmt.Errorf("error unmarshalling event: %w", err),
}
return
} else if resp.Event == "error" {
streamChannel <- ChatMessageStreamChannelResponse{
Err: errors.New("error streaming event: " + string(line)),
}
return
} else if resp.Answer == "" {
return
}
streamChannel <- resp
}
}
}