-
Notifications
You must be signed in to change notification settings - Fork 0
/
implement_xfyun.go
274 lines (232 loc) · 6.7 KB
/
implement_xfyun.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
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
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
package pkg_ai
import (
"bufio"
"bytes"
"encoding/json"
"errors"
"github.com/jinzhu/copier"
"io"
)
/**
* 【科大讯飞】xfyun
* Doc : https://www.xfyun.cn/doc/spark/HTTP%E8%B0%83%E7%94%A8%E6%96%87%E6%A1%A3.html#_1-%E6%8E%A5%E5%8F%A3%E8%AF%B4%E6%98%8E
*/
type XfYunConf struct {
Url string `json:"url"`
Key string `json:"key"`
}
func NewXfYunConf(url, key string) *Config {
return &Config{XfYunUrl: url, XfYunKey: key}
}
type XfYunServer struct {
Conf XfYunConf `json:"conf"`
}
func newXfYunServer(url, key string) *XfYunServer {
return &XfYunServer{
Conf: XfYunConf{
Url: url,
Key: key,
},
}
}
func (x *XfYunServer) Supplier() string {
return "xfyun"
}
func (x *XfYunServer) RequestPath() string {
return x.Conf.Url
}
type XfYunRequestBody struct {
Messages []Message `json:"messages"`
Model string `json:"model"`
MaxTokens int64 `json:"max_tokens,omitempty"`
Temperature float64 `json:"temperature,omitempty"`
Stream bool `json:"stream"`
}
func (x *XfYunServer) build(data RequestData, isStream bool) ([]byte, error) {
if data.UserQuery == "" || data.Model == "" {
return []byte{}, errors.New("问题、模型为必传字段")
}
request := &XfYunRequestBody{Stream: isStream, Messages: make([]Message, 0)}
if err := copier.Copy(request, &data); err != nil {
return nil, err
}
if data.SystemQuery != "" {
request.Messages = append(request.Messages, Message{Role: MessageSystem, Content: data.SystemQuery})
}
if data.History != nil && len(data.History) > 0 {
for _, detail := range data.History {
request.Messages = append(request.Messages, Message{Role: MessageUSer, Content: detail[0]})
request.Messages = append(request.Messages, Message{Role: MessageAssistant, Content: detail[1]})
}
}
request.Messages = append(request.Messages, Message{Role: MessageUSer, Content: data.UserQuery})
return json.Marshal(request)
}
type XfYunChatResponse struct {
Code int64 `json:"code"`
Message string `json:"message"`
Sid string `json:"sid"`
Choices []struct {
Message struct {
Role string `json:"role"`
Content string `json:"content"`
} `json:"message"`
Index int64 `json:"index"`
} `json:"choices"`
Usage struct {
PromptTokens int64 `json:"prompt_tokens"`
CompletionTokens int64 `json:"completion_tokens"`
TotalTokens int64 `json:"total_tokens"`
} `json:"usage"`
Error struct {
Message string `json:"message"`
Type string `json:"type"`
Param interface{} `json:"param"`
Code string `json:"code"`
} `json:"error"`
}
func (x *XfYunServer) Chat(requestPath string, data []byte) (*Response, error) {
headers := map[string]string{"Authorization": "Bearer " + x.Conf.Key}
ret := &Response{RequestHeader: make([]byte, 0), RequestBody: data, ResponseData: make([][]byte, 0)}
ret.RequestHeader, _ = json.Marshal(headers)
response, err := postBase(requestPath, string(data), headers)
if err != nil {
return ret, err
}
defer func() {
_ = response.Body.Close()
}()
retBytes, err := io.ReadAll(response.Body)
ret.ResponseData = append(ret.ResponseData, retBytes)
if err != nil {
return ret, err
}
retStruct := XfYunChatResponse{}
if err := json.Unmarshal(retBytes, &retStruct); err != nil {
return ret, err
}
ret.RequestId = retStruct.Sid
ret.PromptTokens = retStruct.Usage.PromptTokens
ret.CompletionTokens = retStruct.Usage.CompletionTokens
if retStruct.Message != "Success" {
if len(retStruct.Message) > 0 {
return ret, errors.New(retStruct.Message)
} else {
return ret, errors.New(retStruct.Error.Message)
}
}
if len(retStruct.Choices) == 0 {
return ret, errors.New("无有效响应数据")
}
ret.ResponseText = retStruct.Choices[0].Message.Content
return ret, nil
}
type XfYunStreamResp struct {
Code int64 `json:"code"`
Message string `json:"message"`
Sid string `json:"sid"`
ID string `json:"id"`
Created int `json:"created"`
Choices []struct {
Delta struct {
Role string `json:"role"`
Content string `json:"content"`
} `json:"delta"`
Index int64 `json:"index"`
} `json:"choices"`
Usage struct {
PromptTokens int64 `json:"prompt_tokens"`
CompletionTokens int64 `json:"completion_tokens"`
TotalTokens int64 `json:"total_tokens"`
} `json:"usage"`
Error struct {
Message string `json:"message"`
Type string `json:"type"`
Param interface{} `json:"param"`
Code string `json:"code"`
} `json:"error"`
}
type XfYunErrorInfo struct {
Message string `json:"message"`
Error struct {
Message string `json:"message"`
Type string `json:"type"`
Param interface{} `json:"param"`
Code string `json:"code"`
} `json:"error"`
}
func (x *XfYunServer) ChatStream(requestPath string, data []byte, msgCh chan string, errChan chan error) (*Response, error) {
headers := map[string]string{"Authorization": "Bearer " + x.Conf.Key}
ret := &Response{RequestHeader: make([]byte, 0), RequestBody: data, ResponseData: make([][]byte, 0)}
ret.RequestHeader, _ = json.Marshal(headers)
response, err := postBase(requestPath, string(data), headers)
if err != nil {
errChan <- err
return ret, err
}
defer func() {
_ = response.Body.Close()
}()
reader := bufio.NewReader(response.Body)
for {
line, err := reader.ReadBytes('\n')
ret.ResponseData = append(ret.ResponseData, line)
line = bytes.TrimSuffix(line, []byte("\n"))
if err != nil {
if errors.Is(err, io.EOF) {
resErr := err
errStruct := &XfYunErrorInfo{}
if err := json.Unmarshal(line, errStruct); err == nil {
if len(errStruct.Message) > 0 {
resErr = errors.New(errStruct.Message)
} else {
resErr = errors.New(errStruct.Error.Message)
}
}
errChan <- resErr
return ret, resErr
}
errChan <- err
return ret, err
}
if string(line) == "" {
continue
}
headerData := []byte("data: ")
if !bytes.HasPrefix(line, headerData) {
continue
}
line = bytes.TrimPrefix(line, headerData)
if string(line) == "[DONE]" {
close(msgCh)
break
}
retStruct := XfYunStreamResp{}
if err := json.Unmarshal(line, &retStruct); err != nil {
errChan <- err
return ret, err
}
if retStruct.Message != "Success" {
if len(retStruct.Message) > 0 {
err = errors.New(retStruct.Message)
} else {
err = errors.New(retStruct.Error.Message)
}
errChan <- err
return ret, err
}
if len(retStruct.Choices) == 0 {
continue
}
ret.ResponseText += retStruct.Choices[0].Delta.Content
msgCh <- retStruct.Choices[0].Delta.Content
if retStruct.Usage.TotalTokens > 0 {
ret.RequestId = retStruct.Sid
ret.PromptTokens = retStruct.Usage.PromptTokens
ret.CompletionTokens = retStruct.Usage.CompletionTokens
close(msgCh)
break
}
}
return ret, nil
}