This repository has been archived by the owner on Mar 29, 2024. It is now read-only.
/
main.go
344 lines (294 loc) Β· 9.37 KB
/
main.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
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
package openai
import (
_ "embed"
"encoding/base64"
"encoding/json"
"fmt"
"sync"
"github.com/gabriel-vasile/mimetype"
"github.com/gofrs/uuid"
"go.uber.org/zap"
"google.golang.org/protobuf/encoding/protojson"
"google.golang.org/protobuf/types/known/structpb"
"github.com/instill-ai/component/pkg/base"
pipelinePB "github.com/instill-ai/protogen-go/vdp/pipeline/v1beta"
"github.com/instill-ai/x/errmsg"
)
const (
host = "https://api.openai.com"
textGenerationTask = "TASK_TEXT_GENERATION"
textEmbeddingsTask = "TASK_TEXT_EMBEDDINGS"
speechRecognitionTask = "TASK_SPEECH_RECOGNITION"
textToSpeechTask = "TASK_TEXT_TO_SPEECH"
textToImageTask = "TASK_TEXT_TO_IMAGE"
)
var (
//go:embed config/definitions.json
definitionsJSON []byte
//go:embed config/tasks.json
tasksJSON []byte
//go:embed config/openai.json
openAIJSON []byte
once sync.Once
connector base.IConnector
)
type Connector struct {
base.Connector
}
type Execution struct {
base.Execution
}
func Init(logger *zap.Logger) base.IConnector {
once.Do(func() {
connector = &Connector{
Connector: base.Connector{
Component: base.Component{Logger: logger},
},
}
err := connector.LoadConnectorDefinitions(definitionsJSON, tasksJSON, map[string][]byte{"openai.json": openAIJSON})
if err != nil {
logger.Fatal(err.Error())
}
})
return connector
}
func (c *Connector) CreateExecution(defUID uuid.UUID, task string, config *structpb.Struct, logger *zap.Logger) (base.IExecution, error) {
e := &Execution{}
e.Execution = base.CreateExecutionHelper(e, c, defUID, task, config, logger)
return e, nil
}
// getBasePath returns OpenAI's API URL. This configuration param allows us to
// override the API the connector will point to. It isn't meant to be exposed
// to users. Rather, it can serve to test the logic against a fake server.
// TODO instead of having the API value hardcoded in the codebase, it should be
// read from a config file or environment variable.
func getBasePath(config *structpb.Struct) string {
v, ok := config.GetFields()["base_path"]
if !ok {
return host
}
return v.GetStringValue()
}
func getAPIKey(config *structpb.Struct) string {
return config.GetFields()["api_key"].GetStringValue()
}
func getOrg(config *structpb.Struct) string {
val, ok := config.GetFields()["organization"]
if !ok {
return ""
}
return val.GetStringValue()
}
func (e *Execution) Execute(inputs []*structpb.Struct) ([]*structpb.Struct, error) {
client := newClient(e.Config, e.Logger)
outputs := []*structpb.Struct{}
for _, input := range inputs {
switch e.Task {
case textGenerationTask:
inputStruct := TextCompletionInput{}
err := base.ConvertFromStructpb(input, &inputStruct)
if err != nil {
return nil, err
}
messages := []interface{}{}
// If chat history is provided, add it to the messages, and ignore the system message
if inputStruct.ChatHistory != nil {
for _, chat := range inputStruct.ChatHistory {
if chat.Role == "user" {
messages = append(messages, MultiModalMessage{Role: chat.Role, Content: chat.Content})
} else {
content := ""
for _, c := range chat.Content {
// OpenAI doesn't support MultiModal Content for non-user role
if c.Type == "text" {
content = *c.Text
}
}
messages = append(messages, Message{Role: chat.Role, Content: content})
}
}
} else {
// If chat history is not provided, add the system message to the messages
if inputStruct.SystemMessage != nil {
messages = append(messages, Message{Role: "system", Content: *inputStruct.SystemMessage})
}
}
userContents := []Content{}
userContents = append(userContents, Content{Type: "text", Text: &inputStruct.Prompt})
for _, image := range inputStruct.Images {
b, err := base64.StdEncoding.DecodeString(base.TrimBase64Mime(image))
if err != nil {
return nil, err
}
url := fmt.Sprintf("data:%s;base64,%s", mimetype.Detect(b).String(), base.TrimBase64Mime(image))
userContents = append(userContents, Content{Type: "image_url", ImageURL: &ImageURL{URL: url}})
}
messages = append(messages, MultiModalMessage{Role: "user", Content: userContents})
body := TextCompletionReq{
Messages: messages,
Model: inputStruct.Model,
MaxTokens: inputStruct.MaxTokens,
Temperature: inputStruct.Temperature,
N: inputStruct.N,
TopP: inputStruct.TopP,
PresencePenalty: inputStruct.PresencePenalty,
FrequencyPenalty: inputStruct.FrequencyPenalty,
}
// workaround, the OpenAI service can not accept this param
if inputStruct.Model != "gpt-4-vision-preview" {
body.ResponseFormat = inputStruct.ResponseFormat
}
resp := TextCompletionResp{}
req := client.R().SetResult(&resp).SetBody(body)
if _, err := req.Post(completionsPath); err != nil {
return inputs, err
}
outputStruct := TextCompletionOutput{
Texts: []string{},
}
for _, c := range resp.Choices {
outputStruct.Texts = append(outputStruct.Texts, c.Message.Content)
}
outputJSON, err := json.Marshal(outputStruct)
if err != nil {
return nil, err
}
output := structpb.Struct{}
err = protojson.Unmarshal(outputJSON, &output)
if err != nil {
return nil, err
}
outputs = append(outputs, &output)
case textEmbeddingsTask:
inputStruct := TextEmbeddingsInput{}
err := base.ConvertFromStructpb(input, &inputStruct)
if err != nil {
return nil, err
}
resp := TextEmbeddingsResp{}
req := client.R().SetBody(TextEmbeddingsReq{
Model: inputStruct.Model,
Input: []string{inputStruct.Text},
}).SetResult(&resp)
if _, err := req.Post(embeddingsPath); err != nil {
return inputs, err
}
outputStruct := TextEmbeddingsOutput{
Embedding: resp.Data[0].Embedding,
}
output, err := base.ConvertToStructpb(outputStruct)
if err != nil {
return nil, err
}
outputs = append(outputs, output)
case speechRecognitionTask:
inputStruct := AudioTranscriptionInput{}
err := base.ConvertFromStructpb(input, &inputStruct)
if err != nil {
return nil, err
}
audioBytes, err := base64.StdEncoding.DecodeString(base.TrimBase64Mime(inputStruct.Audio))
if err != nil {
return nil, err
}
data, ct, err := getBytes(AudioTranscriptionReq{
File: audioBytes,
Model: inputStruct.Model,
Prompt: inputStruct.Prompt,
Language: inputStruct.Prompt,
Temperature: inputStruct.Temperature,
})
if err != nil {
return inputs, err
}
resp := AudioTranscriptionResp{}
req := client.R().SetBody(data).SetResult(&resp).SetHeader("Content-Type", ct)
if _, err := req.Post(transcriptionsPath); err != nil {
return inputs, err
}
output, err := base.ConvertToStructpb(resp)
if err != nil {
return nil, err
}
outputs = append(outputs, output)
case textToSpeechTask:
inputStruct := TextToSpeechInput{}
err := base.ConvertFromStructpb(input, &inputStruct)
if err != nil {
return nil, err
}
req := client.R().SetBody(TextToSpeechReq{
Input: inputStruct.Text,
Model: inputStruct.Model,
Voice: inputStruct.Voice,
ResponseFormat: inputStruct.ResponseFormat,
Speed: inputStruct.Speed,
})
resp, err := req.Post(createSpeechPath)
if err != nil {
return inputs, err
}
audio := base64.StdEncoding.EncodeToString(resp.Body())
outputStruct := TextToSpeechOutput{
Audio: fmt.Sprintf("data:audio/wav;base64,%s", audio),
}
output, err := base.ConvertToStructpb(outputStruct)
if err != nil {
return nil, err
}
outputs = append(outputs, output)
case textToImageTask:
inputStruct := ImagesGenerationInput{}
err := base.ConvertFromStructpb(input, &inputStruct)
if err != nil {
return nil, err
}
resp := ImageGenerationsResp{}
req := client.R().SetBody(ImageGenerationsReq{
Model: inputStruct.Model,
Prompt: inputStruct.Prompt,
Quality: inputStruct.Quality,
Size: inputStruct.Size,
Style: inputStruct.Style,
N: inputStruct.N,
ResponseFormat: "b64_json",
}).SetResult(&resp)
if _, err := req.Post(imgGenerationPath); err != nil {
return inputs, err
}
results := []ImageGenerationsOutputResult{}
for _, data := range resp.Data {
results = append(results, ImageGenerationsOutputResult{
Image: fmt.Sprintf("data:image/webp;base64,%s", data.Image),
RevisedPrompt: data.RevisedPrompt,
})
}
outputStruct := ImageGenerationsOutput{
Results: results,
}
output, err := base.ConvertToStructpb(outputStruct)
if err != nil {
return nil, err
}
outputs = append(outputs, output)
default:
return nil, errmsg.AddMessage(
fmt.Errorf("not supported task: %s", e.Task),
fmt.Sprintf("%s task is not supported.", e.Task),
)
}
}
return outputs, nil
}
// Test checks the connector state.
func (c *Connector) Test(_ uuid.UUID, config *structpb.Struct, logger *zap.Logger) (pipelinePB.Connector_State, error) {
models := ListModelsResponse{}
req := newClient(config, logger).R().SetResult(&models)
if _, err := req.Get(listModelsPath); err != nil {
return pipelinePB.Connector_STATE_ERROR, err
}
if len(models.Data) == 0 {
return pipelinePB.Connector_STATE_DISCONNECTED, nil
}
return pipelinePB.Connector_STATE_CONNECTED, nil
}