-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathfile.go
94 lines (75 loc) · 2.54 KB
/
file.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
package openai
import (
"bytes"
"context"
"fmt"
"github.com/GeniusAI-Platform/openai/client"
"github.com/GeniusAI-Platform/openai/entity"
"github.com/GeniusAI-Platform/openai/errors"
"github.com/GeniusAI-Platform/openai/types"
"github.com/GeniusAI-Platform/openai/utils"
"net/http"
"path/filepath"
)
const (
fileEndpoint = "/files"
fileDynamicEndpoint = "/files/%s"
fileDynamicWithContentEndpoint = "/files/%s/content"
)
type File struct {
client client.Transporter
}
// NewFile create File object to manage file (upload, retrieve, list)
func NewFile(client client.Transporter) *File {
return &File{
client: client,
}
}
// ListFile Returns a list of files that belong to the user's organization
func (f *File) ListFile(ctx context.Context) (*entity.FilesListResponse, error) {
resp, err := f.client.Get(ctx, &client.APIConfig{Path: fileEndpoint})
if err != nil {
return nil, err
}
return responseHandler[*entity.FilesListResponse](resp)
}
// UploadFile Upload a file that contains document(s) to be used across various endpoints/features. Currently, the size of all the files uploaded by one organization can be up to 1 GB. Please contact us if you need to increase the storage limit
func (f *File) UploadFile(ctx context.Context, req entity.FileUploadRequest) (*entity.FileResponse, error) {
if err := f.client.GetValidator().Struct(req); err != nil {
return nil, err
}
body := new(bytes.Buffer)
fb := utils.NewFormBuilder(body)
if filepath.Ext(req.File.Name()) != ".jsonl" {
return nil, errors.ErrFileIsInvalidFormat
}
if err := fb.CreateFormFile("file", req.File); err != nil {
return nil, err
}
if err := fb.WriteField("purpose", req.Purpose); err != nil {
return nil, err
}
if err := fb.Close(); err != nil {
return nil, err
}
resp, err := f.client.PostFile(ctx, &client.APIConfig{Path: fileEndpoint}, body, fb.FormDataContentType())
if err != nil {
return nil, err
}
return responseHandler[*entity.FileResponse](resp)
}
// RetrieveFile Returns information about a specific file or file content
func (f *File) RetrieveFile(ctx context.Context, fileID types.ID, content bool) (*entity.FileResponse, error) {
if fileID.IsEmpty() {
return nil, errors.New(http.StatusBadRequest, "", "fileID is empty", "", "")
}
path := fmt.Sprintf(fileDynamicEndpoint, fileID)
if content {
path = fmt.Sprintf(fileDynamicWithContentEndpoint, fileID)
}
resp, err := f.client.Get(ctx, &client.APIConfig{Path: path})
if err != nil {
return nil, err
}
return responseHandler[*entity.FileResponse](resp)
}