-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathvisionchat.go
More file actions
110 lines (101 loc) · 2.64 KB
/
Copy pathvisionchat.go
File metadata and controls
110 lines (101 loc) · 2.64 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
package openai
import (
"bufio"
"encoding/base64"
"encoding/json"
"errors"
)
type VisionMessage struct {
Content []VisionContent `json:"content"`
Role string `json:"role"`
}
type VisionContent struct {
// VISION_MESSAGE_
Type string `json:"type"`
Text string `json:"text,omitempty"`
ImageUrl *VisionContentImageUrl `json:"image_url,omitempty"`
}
type VisionContentImageUrl struct {
Url string `json:"url"`
// 图片细节:
Detail string `json:"detail,omitempty"`
}
type VisionChatRequest struct {
Messages []VisionMessage `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 realVisionChatStreamError struct {
Code int `json:"code"`
Message string `json:"message"`
}
func checkVisionChatRequest(cr *VisionChatRequest) {
if cr.ResponseFormat.Type == "" {
cr.ResponseFormat.Type = "text"
}
if cr.Temperature == 0 {
cr.Temperature = 0.3
}
if cr.TopP == 0 {
cr.TopP = 1
}
}
func GenerateImageUrlBase64(file []byte) string {
return "data:image/jpeg;base64," + base64.StdEncoding.EncodeToString(file)
}
func (client Client) ChatVisionStream(model string, messages []VisionMessage, during func(string)) error {
reqBody := VisionChatRequest{}
reqBody.Messages = messages
reqBody.Stream = true
reqBody.Model = model
checkVisionChatRequest(&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 {
var resError realVisionChatStreamError
json.Unmarshal([]byte(_res), &resError)
if resError.Code != 0 {
return errors.New(resError.Message)
}
initFlag = false
continue
}
_res = _res[6:]
var _json realChatStreamResponse
e := json.Unmarshal([]byte(_res), &_json)
if e != nil {
return e
}
during(_json.Choices[0].Delta.Content)
}
return nil
}