file.go

  1// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
  2
  3package openai
  4
  5import (
  6	"bytes"
  7	"context"
  8	"errors"
  9	"fmt"
 10	"io"
 11	"mime/multipart"
 12	"net/http"
 13	"net/url"
 14
 15	"github.com/openai/openai-go/internal/apiform"
 16	"github.com/openai/openai-go/internal/apijson"
 17	"github.com/openai/openai-go/internal/apiquery"
 18	"github.com/openai/openai-go/internal/requestconfig"
 19	"github.com/openai/openai-go/option"
 20	"github.com/openai/openai-go/packages/pagination"
 21	"github.com/openai/openai-go/packages/param"
 22	"github.com/openai/openai-go/packages/resp"
 23	"github.com/openai/openai-go/shared/constant"
 24)
 25
 26// FileService contains methods and other services that help with interacting with
 27// the openai API.
 28//
 29// Note, unlike clients, this service does not read variables from the environment
 30// automatically. You should not instantiate this service directly, and instead use
 31// the [NewFileService] method instead.
 32type FileService struct {
 33	Options []option.RequestOption
 34}
 35
 36// NewFileService generates a new service that applies the given options to each
 37// request. These options are applied after the parent client's options (if there
 38// is one), and before any request-specific options.
 39func NewFileService(opts ...option.RequestOption) (r FileService) {
 40	r = FileService{}
 41	r.Options = opts
 42	return
 43}
 44
 45// Upload a file that can be used across various endpoints. Individual files can be
 46// up to 512 MB, and the size of all files uploaded by one organization can be up
 47// to 100 GB.
 48//
 49// The Assistants API supports files up to 2 million tokens and of specific file
 50// types. See the
 51// [Assistants Tools guide](https://platform.openai.com/docs/assistants/tools) for
 52// details.
 53//
 54// The Fine-tuning API only supports `.jsonl` files. The input also has certain
 55// required formats for fine-tuning
 56// [chat](https://platform.openai.com/docs/api-reference/fine-tuning/chat-input) or
 57// [completions](https://platform.openai.com/docs/api-reference/fine-tuning/completions-input)
 58// models.
 59//
 60// The Batch API only supports `.jsonl` files up to 200 MB in size. The input also
 61// has a specific required
 62// [format](https://platform.openai.com/docs/api-reference/batch/request-input).
 63//
 64// Please [contact us](https://help.openai.com/) if you need to increase these
 65// storage limits.
 66func (r *FileService) New(ctx context.Context, body FileNewParams, opts ...option.RequestOption) (res *FileObject, err error) {
 67	opts = append(r.Options[:], opts...)
 68	path := "files"
 69	err = requestconfig.ExecuteNewRequest(ctx, http.MethodPost, path, body, &res, opts...)
 70	return
 71}
 72
 73// Returns information about a specific file.
 74func (r *FileService) Get(ctx context.Context, fileID string, opts ...option.RequestOption) (res *FileObject, err error) {
 75	opts = append(r.Options[:], opts...)
 76	if fileID == "" {
 77		err = errors.New("missing required file_id parameter")
 78		return
 79	}
 80	path := fmt.Sprintf("files/%s", fileID)
 81	err = requestconfig.ExecuteNewRequest(ctx, http.MethodGet, path, nil, &res, opts...)
 82	return
 83}
 84
 85// Returns a list of files.
 86func (r *FileService) List(ctx context.Context, query FileListParams, opts ...option.RequestOption) (res *pagination.CursorPage[FileObject], err error) {
 87	var raw *http.Response
 88	opts = append(r.Options[:], opts...)
 89	opts = append([]option.RequestOption{option.WithResponseInto(&raw)}, opts...)
 90	path := "files"
 91	cfg, err := requestconfig.NewRequestConfig(ctx, http.MethodGet, path, query, &res, opts...)
 92	if err != nil {
 93		return nil, err
 94	}
 95	err = cfg.Execute()
 96	if err != nil {
 97		return nil, err
 98	}
 99	res.SetPageConfig(cfg, raw)
100	return res, nil
101}
102
103// Returns a list of files.
104func (r *FileService) ListAutoPaging(ctx context.Context, query FileListParams, opts ...option.RequestOption) *pagination.CursorPageAutoPager[FileObject] {
105	return pagination.NewCursorPageAutoPager(r.List(ctx, query, opts...))
106}
107
108// Delete a file.
109func (r *FileService) Delete(ctx context.Context, fileID string, opts ...option.RequestOption) (res *FileDeleted, err error) {
110	opts = append(r.Options[:], opts...)
111	if fileID == "" {
112		err = errors.New("missing required file_id parameter")
113		return
114	}
115	path := fmt.Sprintf("files/%s", fileID)
116	err = requestconfig.ExecuteNewRequest(ctx, http.MethodDelete, path, nil, &res, opts...)
117	return
118}
119
120// Returns the contents of the specified file.
121func (r *FileService) Content(ctx context.Context, fileID string, opts ...option.RequestOption) (res *http.Response, err error) {
122	opts = append(r.Options[:], opts...)
123	opts = append([]option.RequestOption{option.WithHeader("Accept", "application/binary")}, opts...)
124	if fileID == "" {
125		err = errors.New("missing required file_id parameter")
126		return
127	}
128	path := fmt.Sprintf("files/%s/content", fileID)
129	err = requestconfig.ExecuteNewRequest(ctx, http.MethodGet, path, nil, &res, opts...)
130	return
131}
132
133type FileDeleted struct {
134	ID      string        `json:"id,required"`
135	Deleted bool          `json:"deleted,required"`
136	Object  constant.File `json:"object,required"`
137	// Metadata for the response, check the presence of optional fields with the
138	// [resp.Field.IsPresent] method.
139	JSON struct {
140		ID          resp.Field
141		Deleted     resp.Field
142		Object      resp.Field
143		ExtraFields map[string]resp.Field
144		raw         string
145	} `json:"-"`
146}
147
148// Returns the unmodified JSON received from the API
149func (r FileDeleted) RawJSON() string { return r.JSON.raw }
150func (r *FileDeleted) UnmarshalJSON(data []byte) error {
151	return apijson.UnmarshalRoot(data, r)
152}
153
154// The `File` object represents a document that has been uploaded to OpenAI.
155type FileObject struct {
156	// The file identifier, which can be referenced in the API endpoints.
157	ID string `json:"id,required"`
158	// The size of the file, in bytes.
159	Bytes int64 `json:"bytes,required"`
160	// The Unix timestamp (in seconds) for when the file was created.
161	CreatedAt int64 `json:"created_at,required"`
162	// The name of the file.
163	Filename string `json:"filename,required"`
164	// The object type, which is always `file`.
165	Object constant.File `json:"object,required"`
166	// The intended purpose of the file. Supported values are `assistants`,
167	// `assistants_output`, `batch`, `batch_output`, `fine-tune`, `fine-tune-results`
168	// and `vision`.
169	//
170	// Any of "assistants", "assistants_output", "batch", "batch_output", "fine-tune",
171	// "fine-tune-results", "vision".
172	Purpose FileObjectPurpose `json:"purpose,required"`
173	// Deprecated. The current status of the file, which can be either `uploaded`,
174	// `processed`, or `error`.
175	//
176	// Any of "uploaded", "processed", "error".
177	//
178	// Deprecated: deprecated
179	Status FileObjectStatus `json:"status,required"`
180	// The Unix timestamp (in seconds) for when the file will expire.
181	ExpiresAt int64 `json:"expires_at"`
182	// Deprecated. For details on why a fine-tuning training file failed validation,
183	// see the `error` field on `fine_tuning.job`.
184	//
185	// Deprecated: deprecated
186	StatusDetails string `json:"status_details"`
187	// Metadata for the response, check the presence of optional fields with the
188	// [resp.Field.IsPresent] method.
189	JSON struct {
190		ID            resp.Field
191		Bytes         resp.Field
192		CreatedAt     resp.Field
193		Filename      resp.Field
194		Object        resp.Field
195		Purpose       resp.Field
196		Status        resp.Field
197		ExpiresAt     resp.Field
198		StatusDetails resp.Field
199		ExtraFields   map[string]resp.Field
200		raw           string
201	} `json:"-"`
202}
203
204// Returns the unmodified JSON received from the API
205func (r FileObject) RawJSON() string { return r.JSON.raw }
206func (r *FileObject) UnmarshalJSON(data []byte) error {
207	return apijson.UnmarshalRoot(data, r)
208}
209
210// The intended purpose of the file. Supported values are `assistants`,
211// `assistants_output`, `batch`, `batch_output`, `fine-tune`, `fine-tune-results`
212// and `vision`.
213type FileObjectPurpose string
214
215const (
216	FileObjectPurposeAssistants       FileObjectPurpose = "assistants"
217	FileObjectPurposeAssistantsOutput FileObjectPurpose = "assistants_output"
218	FileObjectPurposeBatch            FileObjectPurpose = "batch"
219	FileObjectPurposeBatchOutput      FileObjectPurpose = "batch_output"
220	FileObjectPurposeFineTune         FileObjectPurpose = "fine-tune"
221	FileObjectPurposeFineTuneResults  FileObjectPurpose = "fine-tune-results"
222	FileObjectPurposeVision           FileObjectPurpose = "vision"
223)
224
225// Deprecated. The current status of the file, which can be either `uploaded`,
226// `processed`, or `error`.
227type FileObjectStatus string
228
229const (
230	FileObjectStatusUploaded  FileObjectStatus = "uploaded"
231	FileObjectStatusProcessed FileObjectStatus = "processed"
232	FileObjectStatusError     FileObjectStatus = "error"
233)
234
235// The intended purpose of the uploaded file. One of: - `assistants`: Used in the
236// Assistants API - `batch`: Used in the Batch API - `fine-tune`: Used for
237// fine-tuning - `vision`: Images used for vision fine-tuning - `user_data`:
238// Flexible file type for any purpose - `evals`: Used for eval data sets
239type FilePurpose string
240
241const (
242	FilePurposeAssistants FilePurpose = "assistants"
243	FilePurposeBatch      FilePurpose = "batch"
244	FilePurposeFineTune   FilePurpose = "fine-tune"
245	FilePurposeVision     FilePurpose = "vision"
246	FilePurposeUserData   FilePurpose = "user_data"
247	FilePurposeEvals      FilePurpose = "evals"
248)
249
250type FileNewParams struct {
251	// The File object (not file name) to be uploaded.
252	File io.Reader `json:"file,required" format:"binary"`
253	// The intended purpose of the uploaded file. One of: - `assistants`: Used in the
254	// Assistants API - `batch`: Used in the Batch API - `fine-tune`: Used for
255	// fine-tuning - `vision`: Images used for vision fine-tuning - `user_data`:
256	// Flexible file type for any purpose - `evals`: Used for eval data sets
257	//
258	// Any of "assistants", "batch", "fine-tune", "vision", "user_data", "evals".
259	Purpose FilePurpose `json:"purpose,omitzero,required"`
260	paramObj
261}
262
263// IsPresent returns true if the field's value is not omitted and not the JSON
264// "null". To check if this field is omitted, use [param.IsOmitted].
265func (f FileNewParams) IsPresent() bool { return !param.IsOmitted(f) && !f.IsNull() }
266
267func (r FileNewParams) MarshalMultipart() (data []byte, contentType string, err error) {
268	buf := bytes.NewBuffer(nil)
269	writer := multipart.NewWriter(buf)
270	err = apiform.MarshalRoot(r, writer)
271	if err != nil {
272		writer.Close()
273		return nil, "", err
274	}
275	err = writer.Close()
276	if err != nil {
277		return nil, "", err
278	}
279	return buf.Bytes(), writer.FormDataContentType(), nil
280}
281
282type FileListParams struct {
283	// A cursor for use in pagination. `after` is an object ID that defines your place
284	// in the list. For instance, if you make a list request and receive 100 objects,
285	// ending with obj_foo, your subsequent call can include after=obj_foo in order to
286	// fetch the next page of the list.
287	After param.Opt[string] `query:"after,omitzero" json:"-"`
288	// A limit on the number of objects to be returned. Limit can range between 1 and
289	// 10,000, and the default is 10,000.
290	Limit param.Opt[int64] `query:"limit,omitzero" json:"-"`
291	// Only return files with the given purpose.
292	Purpose param.Opt[string] `query:"purpose,omitzero" json:"-"`
293	// Sort order by the `created_at` timestamp of the objects. `asc` for ascending
294	// order and `desc` for descending order.
295	//
296	// Any of "asc", "desc".
297	Order FileListParamsOrder `query:"order,omitzero" json:"-"`
298	paramObj
299}
300
301// IsPresent returns true if the field's value is not omitted and not the JSON
302// "null". To check if this field is omitted, use [param.IsOmitted].
303func (f FileListParams) IsPresent() bool { return !param.IsOmitted(f) && !f.IsNull() }
304
305// URLQuery serializes [FileListParams]'s query parameters as `url.Values`.
306func (r FileListParams) URLQuery() (v url.Values) {
307	return apiquery.MarshalWithSettings(r, apiquery.QuerySettings{
308		ArrayFormat:  apiquery.ArrayQueryFormatBrackets,
309		NestedFormat: apiquery.NestedQueryFormatBrackets,
310	})
311}
312
313// Sort order by the `created_at` timestamp of the objects. `asc` for ascending
314// order and `desc` for descending order.
315type FileListParamsOrder string
316
317const (
318	FileListParamsOrderAsc  FileListParamsOrder = "asc"
319	FileListParamsOrderDesc FileListParamsOrder = "desc"
320)