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/respjson"
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 // JSON contains metadata for fields, check presence with [respjson.Field.Valid].
138 JSON struct {
139 ID respjson.Field
140 Deleted respjson.Field
141 Object respjson.Field
142 ExtraFields map[string]respjson.Field
143 raw string
144 } `json:"-"`
145}
146
147// Returns the unmodified JSON received from the API
148func (r FileDeleted) RawJSON() string { return r.JSON.raw }
149func (r *FileDeleted) UnmarshalJSON(data []byte) error {
150 return apijson.UnmarshalRoot(data, r)
151}
152
153// The `File` object represents a document that has been uploaded to OpenAI.
154type FileObject struct {
155 // The file identifier, which can be referenced in the API endpoints.
156 ID string `json:"id,required"`
157 // The size of the file, in bytes.
158 Bytes int64 `json:"bytes,required"`
159 // The Unix timestamp (in seconds) for when the file was created.
160 CreatedAt int64 `json:"created_at,required"`
161 // The name of the file.
162 Filename string `json:"filename,required"`
163 // The object type, which is always `file`.
164 Object constant.File `json:"object,required"`
165 // The intended purpose of the file. Supported values are `assistants`,
166 // `assistants_output`, `batch`, `batch_output`, `fine-tune`, `fine-tune-results`
167 // and `vision`.
168 //
169 // Any of "assistants", "assistants_output", "batch", "batch_output", "fine-tune",
170 // "fine-tune-results", "vision".
171 Purpose FileObjectPurpose `json:"purpose,required"`
172 // Deprecated. The current status of the file, which can be either `uploaded`,
173 // `processed`, or `error`.
174 //
175 // Any of "uploaded", "processed", "error".
176 //
177 // Deprecated: deprecated
178 Status FileObjectStatus `json:"status,required"`
179 // The Unix timestamp (in seconds) for when the file will expire.
180 ExpiresAt int64 `json:"expires_at"`
181 // Deprecated. For details on why a fine-tuning training file failed validation,
182 // see the `error` field on `fine_tuning.job`.
183 //
184 // Deprecated: deprecated
185 StatusDetails string `json:"status_details"`
186 // JSON contains metadata for fields, check presence with [respjson.Field.Valid].
187 JSON struct {
188 ID respjson.Field
189 Bytes respjson.Field
190 CreatedAt respjson.Field
191 Filename respjson.Field
192 Object respjson.Field
193 Purpose respjson.Field
194 Status respjson.Field
195 ExpiresAt respjson.Field
196 StatusDetails respjson.Field
197 ExtraFields map[string]respjson.Field
198 raw string
199 } `json:"-"`
200}
201
202// Returns the unmodified JSON received from the API
203func (r FileObject) RawJSON() string { return r.JSON.raw }
204func (r *FileObject) UnmarshalJSON(data []byte) error {
205 return apijson.UnmarshalRoot(data, r)
206}
207
208// The intended purpose of the file. Supported values are `assistants`,
209// `assistants_output`, `batch`, `batch_output`, `fine-tune`, `fine-tune-results`
210// and `vision`.
211type FileObjectPurpose string
212
213const (
214 FileObjectPurposeAssistants FileObjectPurpose = "assistants"
215 FileObjectPurposeAssistantsOutput FileObjectPurpose = "assistants_output"
216 FileObjectPurposeBatch FileObjectPurpose = "batch"
217 FileObjectPurposeBatchOutput FileObjectPurpose = "batch_output"
218 FileObjectPurposeFineTune FileObjectPurpose = "fine-tune"
219 FileObjectPurposeFineTuneResults FileObjectPurpose = "fine-tune-results"
220 FileObjectPurposeVision FileObjectPurpose = "vision"
221)
222
223// Deprecated. The current status of the file, which can be either `uploaded`,
224// `processed`, or `error`.
225type FileObjectStatus string
226
227const (
228 FileObjectStatusUploaded FileObjectStatus = "uploaded"
229 FileObjectStatusProcessed FileObjectStatus = "processed"
230 FileObjectStatusError FileObjectStatus = "error"
231)
232
233// The intended purpose of the uploaded file. One of: - `assistants`: Used in the
234// Assistants API - `batch`: Used in the Batch API - `fine-tune`: Used for
235// fine-tuning - `vision`: Images used for vision fine-tuning - `user_data`:
236// Flexible file type for any purpose - `evals`: Used for eval data sets
237type FilePurpose string
238
239const (
240 FilePurposeAssistants FilePurpose = "assistants"
241 FilePurposeBatch FilePurpose = "batch"
242 FilePurposeFineTune FilePurpose = "fine-tune"
243 FilePurposeVision FilePurpose = "vision"
244 FilePurposeUserData FilePurpose = "user_data"
245 FilePurposeEvals FilePurpose = "evals"
246)
247
248type FileNewParams struct {
249 // The File object (not file name) to be uploaded.
250 File io.Reader `json:"file,omitzero,required" format:"binary"`
251 // The intended purpose of the uploaded file. One of: - `assistants`: Used in the
252 // Assistants API - `batch`: Used in the Batch API - `fine-tune`: Used for
253 // fine-tuning - `vision`: Images used for vision fine-tuning - `user_data`:
254 // Flexible file type for any purpose - `evals`: Used for eval data sets
255 //
256 // Any of "assistants", "batch", "fine-tune", "vision", "user_data", "evals".
257 Purpose FilePurpose `json:"purpose,omitzero,required"`
258 paramObj
259}
260
261func (r FileNewParams) MarshalMultipart() (data []byte, contentType string, err error) {
262 buf := bytes.NewBuffer(nil)
263 writer := multipart.NewWriter(buf)
264 err = apiform.MarshalRoot(r, writer)
265 if err == nil {
266 err = apiform.WriteExtras(writer, r.ExtraFields())
267 }
268 if err != nil {
269 writer.Close()
270 return nil, "", err
271 }
272 err = writer.Close()
273 if err != nil {
274 return nil, "", err
275 }
276 return buf.Bytes(), writer.FormDataContentType(), nil
277}
278
279type FileListParams struct {
280 // A cursor for use in pagination. `after` is an object ID that defines your place
281 // in the list. For instance, if you make a list request and receive 100 objects,
282 // ending with obj_foo, your subsequent call can include after=obj_foo in order to
283 // fetch the next page of the list.
284 After param.Opt[string] `query:"after,omitzero" json:"-"`
285 // A limit on the number of objects to be returned. Limit can range between 1 and
286 // 10,000, and the default is 10,000.
287 Limit param.Opt[int64] `query:"limit,omitzero" json:"-"`
288 // Only return files with the given purpose.
289 Purpose param.Opt[string] `query:"purpose,omitzero" json:"-"`
290 // Sort order by the `created_at` timestamp of the objects. `asc` for ascending
291 // order and `desc` for descending order.
292 //
293 // Any of "asc", "desc".
294 Order FileListParamsOrder `query:"order,omitzero" json:"-"`
295 paramObj
296}
297
298// URLQuery serializes [FileListParams]'s query parameters as `url.Values`.
299func (r FileListParams) URLQuery() (v url.Values, err error) {
300 return apiquery.MarshalWithSettings(r, apiquery.QuerySettings{
301 ArrayFormat: apiquery.ArrayQueryFormatBrackets,
302 NestedFormat: apiquery.NestedQueryFormatBrackets,
303 })
304}
305
306// Sort order by the `created_at` timestamp of the objects. `asc` for ascending
307// order and `desc` for descending order.
308type FileListParamsOrder string
309
310const (
311 FileListParamsOrderAsc FileListParamsOrder = "asc"
312 FileListParamsOrderDesc FileListParamsOrder = "desc"
313)