feat: support direct bytes for file upload (#568)

* feat: support direct bytes for file upload

* add test for errors

* add coverage
This commit is contained in:
Donnie Flood
2023-11-15 09:08:48 -07:00
committed by GitHub
parent fe67abb97e
commit 71848ccf69
4 changed files with 115 additions and 0 deletions

View File

@@ -15,6 +15,24 @@ type FileRequest struct {
Purpose string `json:"purpose"`
}
// PurposeType represents the purpose of the file when uploading.
type PurposeType string
const (
PurposeFineTune PurposeType = "fine-tune"
PurposeAssistants PurposeType = "assistants"
)
// FileBytesRequest represents a file upload request.
type FileBytesRequest struct {
// the name of the uploaded file in OpenAI
Name string
// the bytes of the file
Bytes []byte
// the purpose of the file
Purpose PurposeType
}
// File struct represents an OpenAPI file.
type File struct {
Bytes int `json:"bytes"`
@@ -36,6 +54,37 @@ type FilesList struct {
httpHeader
}
// CreateFileBytes uploads bytes directly to OpenAI without requiring a local file.
func (c *Client) CreateFileBytes(ctx context.Context, request FileBytesRequest) (file File, err error) {
var b bytes.Buffer
reader := bytes.NewReader(request.Bytes)
builder := c.createFormBuilder(&b)
err = builder.WriteField("purpose", string(request.Purpose))
if err != nil {
return
}
err = builder.CreateFormFileReader("file", reader, request.Name)
if err != nil {
return
}
err = builder.Close()
if err != nil {
return
}
req, err := c.newRequest(ctx, http.MethodPost, c.fullURL("/files"),
withBody(&b), withContentType(builder.FormDataContentType()))
if err != nil {
return
}
err = c.sendRequest(req, &file)
return
}
// CreateFile uploads a jsonl file to GPT3
// FilePath must be a local file path.
func (c *Client) CreateFile(ctx context.Context, request FileRequest) (file File, err error) {