-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathchat.go
More file actions
364 lines (351 loc) · 8.96 KB
/
chat.go
File metadata and controls
364 lines (351 loc) · 8.96 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
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
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
package openai
import (
"bufio"
"encoding/json"
"errors"
"strings"
)
type Message struct {
Content string `json:"content"`
Role string `json:"role"`
}
type ChatRequest struct {
Messages []Message `json:"messages"`
Model string `json:"model"`
FrequencyPenalty int `json:"frequency_penalty"`
MaxTokens int `json:"max_tokens,omitempty"`
PresencePenalty int `json:"presence_penalty"`
ResponseFormat struct {
Type string `json:"type"`
} `json:"response_format"`
Stop []string `json:"stop"`
Stream bool `json:"stream"`
Temperature float32 `json:"temperature"`
TopP int `json:"top_p"`
}
type realChatResponse struct {
ID string `json:"id"`
Choices []struct {
FinishReason string `json:"finish_reason"`
Index int `json:"index"`
Message Message `json:"message"`
} `json:"choices"`
Created int `json:"created"`
Model string `json:"model"`
Object string `json:"object"`
Usage struct {
CompletionTokens int `json:"completion_tokens"`
PromptTokens int `json:"prompt_tokens"`
TotalTokens int `json:"total_tokens"`
} `json:"usage"`
}
type realChatStreamResponse struct {
ID string `json:"id"`
Object string `json:"object"`
Created int `json:"created"`
Model string `json:"model"`
SystemFingerprint string `json:"system_fingerprint"`
Choices []struct {
Index int `json:"index"`
Delta struct {
Content string `json:"content"`
} `json:"delta"`
Logprobs interface{} `json:"logprobs"`
FinishReason string `json:"finish_reason"`
} `json:"choices"`
}
type realChatReasonStreamResponse struct {
ID string `json:"id"`
Object string `json:"object"`
Created int `json:"created"`
Model string `json:"model"`
SystemFingerprint string `json:"system_fingerprint"`
Choices []struct {
Index int `json:"index"`
Delta struct {
Content string `json:"content"`
ReasoningContent string `json:"reasoning_content"`
} `json:"delta"`
Logprobs interface{} `json:"logprobs"`
FinishReason interface{} `json:"finish_reason"`
} `json:"choices"`
}
func checkChatRequest(cr *ChatRequest) {
if cr.ResponseFormat.Type == "" {
cr.ResponseFormat.Type = "text"
}
if cr.Temperature == 0 {
cr.Temperature = 0.3
}
if cr.TopP == 0 {
cr.TopP = 1
}
}
// api /chat/completions 的实现
func (client Client) Chat(model string, messages []Message) (*Message, error) {
reqBody := ChatRequest{}
reqBody.Messages = messages
reqBody.Stream = false
reqBody.Model = model
checkChatRequest(&reqBody)
reqClient := client.newHttpClient()
jsonBody, e := json.Marshal(reqBody)
if e != nil {
return nil, e
}
reqClient.SetBody(string(jsonBody))
res := &realChatResponse{}
reqClient.SetResult(res)
httpres, e := reqClient.Post(client.Config.BaseUrl + "/chat/completions")
if e != nil {
return nil, e
}
if httpres.StatusCode() != 200 {
errorMessage, e := parseRealError(httpres.Body())
if e != nil {
return nil, errors.New(string(httpres.Body()))
}
return nil, errors.New(errorMessage)
}
if len(res.Choices) == 0 {
return &Message{}, nil
}
return &res.Choices[0].Message, nil
}
// api /chat/completions 的傻瓜式实现
// 没有上下文,给入提示词和问题即可获得答案
func (client Client) EasyChat(model string, prompt string, message string) (string, error) {
reqBody := ChatRequest{}
reqBody.Messages = []Message{
{Content: prompt, Role: "system"},
{Content: message, Role: "user"},
}
reqBody.Stream = false
reqBody.Model = model
checkChatRequest(&reqBody)
reqClient := client.newHttpClient()
jsonBody, e := json.Marshal(reqBody)
if e != nil {
return "", e
}
reqClient.SetBody(string(jsonBody))
res := &realChatResponse{}
reqClient.SetResult(res)
httpres, e := reqClient.Post(client.Config.BaseUrl + "/chat/completions")
if e != nil {
return "", e
}
if httpres.StatusCode() != 200 {
errorMessage, e := parseRealError(httpres.Body())
if e != nil {
return "", errors.New(string(httpres.Body()))
}
return "", errors.New(errorMessage)
}
if len(res.Choices) == 0 {
return "", nil
}
return res.Choices[0].Message.Content, nil
}
// api /chat/completions 的流式实现
func (client Client) ChatStream(model string, messages []Message, during func(string)) error {
reqBody := ChatRequest{}
reqBody.Messages = messages
reqBody.Stream = true
reqBody.Model = model
reqBody.MaxTokens = client.Config.MaxTokens
checkChatRequest(&reqBody)
reqClient := client.newStreamClient()
jsonBody, e := json.Marshal(reqBody)
if e != nil {
return e
}
reqClient.SetBody(string(jsonBody))
reqClient.SetDoNotParseResponse(true)
httpres, e := reqClient.Post(client.Config.BaseUrl + "/chat/completions")
if e != nil {
return e
}
defer httpres.RawBody().Close()
scanner := bufio.NewScanner(httpres.RawBody())
initFlag := true
for scanner.Scan() {
_res := scanner.Text()
if _res == "" {
continue
}
if strings.HasPrefix(_res, ":") {
continue
}
if _res == "data: [DONE]" {
break
}
if initFlag {
inError := _res
if strings.HasPrefix(_res, "data:") {
inError = inError[6:]
}
resError, e := parseRealError([]byte(inError))
if e != nil {
return errors.New(_res)
}
if resError != "" {
return errors.New(resError)
}
initFlag = false
}
if len(_res) < 7 {
continue
}
_res = _res[6:]
var _json realChatStreamResponse
e := json.Unmarshal([]byte(_res), &_json)
if e != nil {
return e
}
if len(_json.Choices) == 0 {
continue
}
during(_json.Choices[0].Delta.Content)
}
return nil
}
// api /chat/completions 的高自定义度实现
func (client Client) ChatWithConfig(config ChatRequest) (*Message, error) {
config.Stream = false
checkChatRequest(&config)
reqClient := client.newHttpClient()
jsonBody, e := json.Marshal(config)
if e != nil {
return nil, e
}
reqClient.SetBody(string(jsonBody))
res := &realChatResponse{}
reqClient.SetResult(res)
httpres, e := reqClient.Post(client.Config.BaseUrl + "/chat/completions")
if e != nil {
return nil, e
}
if httpres.StatusCode() != 200 {
errorMessage, e := parseRealError(httpres.Body())
if e != nil {
return nil, errors.New(string(httpres.Body()))
}
return nil, errors.New(errorMessage)
}
if len(res.Choices) == 0 {
return &Message{}, nil
}
return &res.Choices[0].Message, nil
}
// api /chat/completions 的高自定义度流式实现
func (client Client) ChatStreamWithConfig(config ChatRequest, during func(string)) error {
config.Stream = true
checkChatRequest(&config)
reqClient := client.newStreamClient()
jsonBody, e := json.Marshal(config)
if e != nil {
return e
}
reqClient.SetBody(string(jsonBody))
reqClient.SetDoNotParseResponse(true)
httpres, e := reqClient.Post(client.Config.BaseUrl + "/chat/completions")
if e != nil {
return e
}
defer httpres.RawBody().Close()
scanner := bufio.NewScanner(httpres.RawBody())
initFlag := true
for scanner.Scan() {
_res := scanner.Text()
if _res == "" {
continue
}
if _res == "data: [DONE]" {
break
}
if initFlag {
resError, e := parseRealError([]byte(_res))
if e == nil {
return errors.New(resError)
}
initFlag = false
continue
}
_res = _res[6:]
var _json realChatStreamResponse
e := json.Unmarshal([]byte(_res), &_json)
if e != nil {
return e
}
if len(_json.Choices) == 0 {
continue
}
during(_json.Choices[0].Delta.Content)
}
return nil
}
// 相比于ChatStream,ChatReasonStream支持了深度思考的模型
func (client Client) ChatReasonStream(model string, messages []Message, think func(string), during func(string)) error {
reqBody := ChatRequest{}
reqBody.Messages = messages
reqBody.Stream = true
reqBody.Model = model
checkChatRequest(&reqBody)
reqClient := client.newStreamClient()
jsonBody, e := json.Marshal(reqBody)
if e != nil {
return e
}
reqClient.SetBody(string(jsonBody))
reqClient.SetDoNotParseResponse(true)
httpres, e := reqClient.Post(client.Config.BaseUrl + "/chat/completions")
if e != nil {
return e
}
defer httpres.RawBody().Close()
scanner := bufio.NewScanner(httpres.RawBody())
initFlag := true
for scanner.Scan() {
_res := scanner.Text()
if _res == "" {
continue
}
if _res == "data: [DONE]" {
break
}
if initFlag {
inError := _res
if strings.HasPrefix(_res, "data:") {
inError = inError[6:]
}
resError, e := parseRealError([]byte(inError))
if e != nil {
return errors.New(_res)
}
if resError != "" {
return errors.New(resError)
}
initFlag = false
}
if len(_res) < 7 {
continue
}
_res = _res[6:]
var _json realChatReasonStreamResponse
e := json.Unmarshal([]byte(_res), &_json)
if e != nil {
return e
}
if len(_json.Choices) == 0 {
continue
}
if _json.Choices[0].Delta.ReasoningContent != "" {
think(_json.Choices[0].Delta.ReasoningContent)
}
if _json.Choices[0].Delta.Content != "" {
during(_json.Choices[0].Delta.Content)
}
}
return nil
}