1// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
2
3package openai
4
5import (
6 "context"
7 "encoding/json"
8 "errors"
9 "fmt"
10 "net/http"
11 "net/url"
12
13 "github.com/openai/openai-go/internal/apijson"
14 "github.com/openai/openai-go/internal/apiquery"
15 "github.com/openai/openai-go/internal/requestconfig"
16 "github.com/openai/openai-go/option"
17 "github.com/openai/openai-go/packages/pagination"
18 "github.com/openai/openai-go/packages/param"
19 "github.com/openai/openai-go/packages/respjson"
20 "github.com/openai/openai-go/shared/constant"
21)
22
23// VectorStoreFileService contains methods and other services that help with
24// interacting with the openai API.
25//
26// Note, unlike clients, this service does not read variables from the environment
27// automatically. You should not instantiate this service directly, and instead use
28// the [NewVectorStoreFileService] method instead.
29type VectorStoreFileService struct {
30 Options []option.RequestOption
31}
32
33// NewVectorStoreFileService generates a new service that applies the given options
34// to each request. These options are applied after the parent client's options (if
35// there is one), and before any request-specific options.
36func NewVectorStoreFileService(opts ...option.RequestOption) (r VectorStoreFileService) {
37 r = VectorStoreFileService{}
38 r.Options = opts
39 return
40}
41
42// Create a vector store file by attaching a
43// [File](https://platform.openai.com/docs/api-reference/files) to a
44// [vector store](https://platform.openai.com/docs/api-reference/vector-stores/object).
45func (r *VectorStoreFileService) New(ctx context.Context, vectorStoreID string, body VectorStoreFileNewParams, opts ...option.RequestOption) (res *VectorStoreFile, err error) {
46 opts = append(r.Options[:], opts...)
47 opts = append([]option.RequestOption{option.WithHeader("OpenAI-Beta", "assistants=v2")}, opts...)
48 if vectorStoreID == "" {
49 err = errors.New("missing required vector_store_id parameter")
50 return
51 }
52 path := fmt.Sprintf("vector_stores/%s/files", vectorStoreID)
53 err = requestconfig.ExecuteNewRequest(ctx, http.MethodPost, path, body, &res, opts...)
54 return
55}
56
57// Create a vector store file by attaching a
58// [File](https://platform.openai.com/docs/api-reference/files) to a
59// [vector store](https://platform.openai.com/docs/api-reference/vector-stores/object).
60//
61// Polls the API and blocks until the task is complete.
62// Default polling interval is 1 second.
63func (r *VectorStoreFileService) NewAndPoll(ctx context.Context, vectorStoreId string, body VectorStoreFileNewParams, pollIntervalMs int, opts ...option.RequestOption) (res *VectorStoreFile, err error) {
64 file, err := r.New(ctx, vectorStoreId, body, opts...)
65 if err != nil {
66 return nil, err
67 }
68 return r.PollStatus(ctx, vectorStoreId, file.ID, pollIntervalMs, opts...)
69}
70
71// Upload a file to the `files` API and then attach it to the given vector store.
72//
73// Note the file will be asynchronously processed (you can use the alternative
74// polling helper method to wait for processing to complete).
75func (r *VectorStoreFileService) Upload(ctx context.Context, vectorStoreID string, body FileNewParams, opts ...option.RequestOption) (*VectorStoreFile, error) {
76 filesService := NewFileService(r.Options...)
77 fileObj, err := filesService.New(ctx, body, opts...)
78 if err != nil {
79 return nil, err
80 }
81 return r.New(ctx, vectorStoreID, VectorStoreFileNewParams{
82 FileID: fileObj.ID,
83 }, opts...)
84}
85
86// Add a file to a vector store and poll until processing is complete.
87// Default polling interval is 1 second.
88func (r *VectorStoreFileService) UploadAndPoll(ctx context.Context, vectorStoreID string, body FileNewParams, pollIntervalMs int, opts ...option.RequestOption) (*VectorStoreFile, error) {
89 res, err := r.Upload(ctx, vectorStoreID, body, opts...)
90 if err != nil {
91 return nil, err
92 }
93 return r.PollStatus(ctx, vectorStoreID, res.ID, pollIntervalMs, opts...)
94}
95
96// Retrieves a vector store file.
97func (r *VectorStoreFileService) Get(ctx context.Context, vectorStoreID string, fileID string, opts ...option.RequestOption) (res *VectorStoreFile, err error) {
98 opts = append(r.Options[:], opts...)
99 opts = append([]option.RequestOption{option.WithHeader("OpenAI-Beta", "assistants=v2")}, opts...)
100 if vectorStoreID == "" {
101 err = errors.New("missing required vector_store_id parameter")
102 return
103 }
104 if fileID == "" {
105 err = errors.New("missing required file_id parameter")
106 return
107 }
108 path := fmt.Sprintf("vector_stores/%s/files/%s", vectorStoreID, fileID)
109 err = requestconfig.ExecuteNewRequest(ctx, http.MethodGet, path, nil, &res, opts...)
110 return
111}
112
113// Update attributes on a vector store file.
114func (r *VectorStoreFileService) Update(ctx context.Context, vectorStoreID string, fileID string, body VectorStoreFileUpdateParams, opts ...option.RequestOption) (res *VectorStoreFile, err error) {
115 opts = append(r.Options[:], opts...)
116 opts = append([]option.RequestOption{option.WithHeader("OpenAI-Beta", "assistants=v2")}, opts...)
117 if vectorStoreID == "" {
118 err = errors.New("missing required vector_store_id parameter")
119 return
120 }
121 if fileID == "" {
122 err = errors.New("missing required file_id parameter")
123 return
124 }
125 path := fmt.Sprintf("vector_stores/%s/files/%s", vectorStoreID, fileID)
126 err = requestconfig.ExecuteNewRequest(ctx, http.MethodPost, path, body, &res, opts...)
127 return
128}
129
130// Returns a list of vector store files.
131func (r *VectorStoreFileService) List(ctx context.Context, vectorStoreID string, query VectorStoreFileListParams, opts ...option.RequestOption) (res *pagination.CursorPage[VectorStoreFile], err error) {
132 var raw *http.Response
133 opts = append(r.Options[:], opts...)
134 opts = append([]option.RequestOption{option.WithHeader("OpenAI-Beta", "assistants=v2"), option.WithResponseInto(&raw)}, opts...)
135 if vectorStoreID == "" {
136 err = errors.New("missing required vector_store_id parameter")
137 return
138 }
139 path := fmt.Sprintf("vector_stores/%s/files", vectorStoreID)
140 cfg, err := requestconfig.NewRequestConfig(ctx, http.MethodGet, path, query, &res, opts...)
141 if err != nil {
142 return nil, err
143 }
144 err = cfg.Execute()
145 if err != nil {
146 return nil, err
147 }
148 res.SetPageConfig(cfg, raw)
149 return res, nil
150}
151
152// Returns a list of vector store files.
153func (r *VectorStoreFileService) ListAutoPaging(ctx context.Context, vectorStoreID string, query VectorStoreFileListParams, opts ...option.RequestOption) *pagination.CursorPageAutoPager[VectorStoreFile] {
154 return pagination.NewCursorPageAutoPager(r.List(ctx, vectorStoreID, query, opts...))
155}
156
157// Delete a vector store file. This will remove the file from the vector store but
158// the file itself will not be deleted. To delete the file, use the
159// [delete file](https://platform.openai.com/docs/api-reference/files/delete)
160// endpoint.
161func (r *VectorStoreFileService) Delete(ctx context.Context, vectorStoreID string, fileID string, opts ...option.RequestOption) (res *VectorStoreFileDeleted, err error) {
162 opts = append(r.Options[:], opts...)
163 opts = append([]option.RequestOption{option.WithHeader("OpenAI-Beta", "assistants=v2")}, opts...)
164 if vectorStoreID == "" {
165 err = errors.New("missing required vector_store_id parameter")
166 return
167 }
168 if fileID == "" {
169 err = errors.New("missing required file_id parameter")
170 return
171 }
172 path := fmt.Sprintf("vector_stores/%s/files/%s", vectorStoreID, fileID)
173 err = requestconfig.ExecuteNewRequest(ctx, http.MethodDelete, path, nil, &res, opts...)
174 return
175}
176
177// Retrieve the parsed contents of a vector store file.
178func (r *VectorStoreFileService) Content(ctx context.Context, vectorStoreID string, fileID string, opts ...option.RequestOption) (res *pagination.Page[VectorStoreFileContentResponse], err error) {
179 var raw *http.Response
180 opts = append(r.Options[:], opts...)
181 opts = append([]option.RequestOption{option.WithHeader("OpenAI-Beta", "assistants=v2"), option.WithResponseInto(&raw)}, opts...)
182 if vectorStoreID == "" {
183 err = errors.New("missing required vector_store_id parameter")
184 return
185 }
186 if fileID == "" {
187 err = errors.New("missing required file_id parameter")
188 return
189 }
190 path := fmt.Sprintf("vector_stores/%s/files/%s/content", vectorStoreID, fileID)
191 cfg, err := requestconfig.NewRequestConfig(ctx, http.MethodGet, path, nil, &res, opts...)
192 if err != nil {
193 return nil, err
194 }
195 err = cfg.Execute()
196 if err != nil {
197 return nil, err
198 }
199 res.SetPageConfig(cfg, raw)
200 return res, nil
201}
202
203// Retrieve the parsed contents of a vector store file.
204func (r *VectorStoreFileService) ContentAutoPaging(ctx context.Context, vectorStoreID string, fileID string, opts ...option.RequestOption) *pagination.PageAutoPager[VectorStoreFileContentResponse] {
205 return pagination.NewPageAutoPager(r.Content(ctx, vectorStoreID, fileID, opts...))
206}
207
208// A list of files attached to a vector store.
209type VectorStoreFile struct {
210 // The identifier, which can be referenced in API endpoints.
211 ID string `json:"id,required"`
212 // The Unix timestamp (in seconds) for when the vector store file was created.
213 CreatedAt int64 `json:"created_at,required"`
214 // The last error associated with this vector store file. Will be `null` if there
215 // are no errors.
216 LastError VectorStoreFileLastError `json:"last_error,required"`
217 // The object type, which is always `vector_store.file`.
218 Object constant.VectorStoreFile `json:"object,required"`
219 // The status of the vector store file, which can be either `in_progress`,
220 // `completed`, `cancelled`, or `failed`. The status `completed` indicates that the
221 // vector store file is ready for use.
222 //
223 // Any of "in_progress", "completed", "cancelled", "failed".
224 Status VectorStoreFileStatus `json:"status,required"`
225 // The total vector store usage in bytes. Note that this may be different from the
226 // original file size.
227 UsageBytes int64 `json:"usage_bytes,required"`
228 // The ID of the
229 // [vector store](https://platform.openai.com/docs/api-reference/vector-stores/object)
230 // that the [File](https://platform.openai.com/docs/api-reference/files) is
231 // attached to.
232 VectorStoreID string `json:"vector_store_id,required"`
233 // Set of 16 key-value pairs that can be attached to an object. This can be useful
234 // for storing additional information about the object in a structured format, and
235 // querying for objects via API or the dashboard. Keys are strings with a maximum
236 // length of 64 characters. Values are strings with a maximum length of 512
237 // characters, booleans, or numbers.
238 Attributes map[string]VectorStoreFileAttributeUnion `json:"attributes,nullable"`
239 // The strategy used to chunk the file.
240 ChunkingStrategy FileChunkingStrategyUnion `json:"chunking_strategy"`
241 // JSON contains metadata for fields, check presence with [respjson.Field.Valid].
242 JSON struct {
243 ID respjson.Field
244 CreatedAt respjson.Field
245 LastError respjson.Field
246 Object respjson.Field
247 Status respjson.Field
248 UsageBytes respjson.Field
249 VectorStoreID respjson.Field
250 Attributes respjson.Field
251 ChunkingStrategy respjson.Field
252 ExtraFields map[string]respjson.Field
253 raw string
254 } `json:"-"`
255}
256
257// Returns the unmodified JSON received from the API
258func (r VectorStoreFile) RawJSON() string { return r.JSON.raw }
259func (r *VectorStoreFile) UnmarshalJSON(data []byte) error {
260 return apijson.UnmarshalRoot(data, r)
261}
262
263// The last error associated with this vector store file. Will be `null` if there
264// are no errors.
265type VectorStoreFileLastError struct {
266 // One of `server_error` or `rate_limit_exceeded`.
267 //
268 // Any of "server_error", "unsupported_file", "invalid_file".
269 Code string `json:"code,required"`
270 // A human-readable description of the error.
271 Message string `json:"message,required"`
272 // JSON contains metadata for fields, check presence with [respjson.Field.Valid].
273 JSON struct {
274 Code respjson.Field
275 Message respjson.Field
276 ExtraFields map[string]respjson.Field
277 raw string
278 } `json:"-"`
279}
280
281// Returns the unmodified JSON received from the API
282func (r VectorStoreFileLastError) RawJSON() string { return r.JSON.raw }
283func (r *VectorStoreFileLastError) UnmarshalJSON(data []byte) error {
284 return apijson.UnmarshalRoot(data, r)
285}
286
287// The status of the vector store file, which can be either `in_progress`,
288// `completed`, `cancelled`, or `failed`. The status `completed` indicates that the
289// vector store file is ready for use.
290type VectorStoreFileStatus string
291
292const (
293 VectorStoreFileStatusInProgress VectorStoreFileStatus = "in_progress"
294 VectorStoreFileStatusCompleted VectorStoreFileStatus = "completed"
295 VectorStoreFileStatusCancelled VectorStoreFileStatus = "cancelled"
296 VectorStoreFileStatusFailed VectorStoreFileStatus = "failed"
297)
298
299// VectorStoreFileAttributeUnion contains all possible properties and values from
300// [string], [float64], [bool].
301//
302// Use the methods beginning with 'As' to cast the union to one of its variants.
303//
304// If the underlying value is not a json object, one of the following properties
305// will be valid: OfString OfFloat OfBool]
306type VectorStoreFileAttributeUnion struct {
307 // This field will be present if the value is a [string] instead of an object.
308 OfString string `json:",inline"`
309 // This field will be present if the value is a [float64] instead of an object.
310 OfFloat float64 `json:",inline"`
311 // This field will be present if the value is a [bool] instead of an object.
312 OfBool bool `json:",inline"`
313 JSON struct {
314 OfString respjson.Field
315 OfFloat respjson.Field
316 OfBool respjson.Field
317 raw string
318 } `json:"-"`
319}
320
321func (u VectorStoreFileAttributeUnion) AsString() (v string) {
322 apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v)
323 return
324}
325
326func (u VectorStoreFileAttributeUnion) AsFloat() (v float64) {
327 apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v)
328 return
329}
330
331func (u VectorStoreFileAttributeUnion) AsBool() (v bool) {
332 apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v)
333 return
334}
335
336// Returns the unmodified JSON received from the API
337func (u VectorStoreFileAttributeUnion) RawJSON() string { return u.JSON.raw }
338
339func (r *VectorStoreFileAttributeUnion) UnmarshalJSON(data []byte) error {
340 return apijson.UnmarshalRoot(data, r)
341}
342
343type VectorStoreFileDeleted struct {
344 ID string `json:"id,required"`
345 Deleted bool `json:"deleted,required"`
346 Object constant.VectorStoreFileDeleted `json:"object,required"`
347 // JSON contains metadata for fields, check presence with [respjson.Field.Valid].
348 JSON struct {
349 ID respjson.Field
350 Deleted respjson.Field
351 Object respjson.Field
352 ExtraFields map[string]respjson.Field
353 raw string
354 } `json:"-"`
355}
356
357// Returns the unmodified JSON received from the API
358func (r VectorStoreFileDeleted) RawJSON() string { return r.JSON.raw }
359func (r *VectorStoreFileDeleted) UnmarshalJSON(data []byte) error {
360 return apijson.UnmarshalRoot(data, r)
361}
362
363type VectorStoreFileContentResponse struct {
364 // The text content
365 Text string `json:"text"`
366 // The content type (currently only `"text"`)
367 Type string `json:"type"`
368 // JSON contains metadata for fields, check presence with [respjson.Field.Valid].
369 JSON struct {
370 Text respjson.Field
371 Type respjson.Field
372 ExtraFields map[string]respjson.Field
373 raw string
374 } `json:"-"`
375}
376
377// Returns the unmodified JSON received from the API
378func (r VectorStoreFileContentResponse) RawJSON() string { return r.JSON.raw }
379func (r *VectorStoreFileContentResponse) UnmarshalJSON(data []byte) error {
380 return apijson.UnmarshalRoot(data, r)
381}
382
383type VectorStoreFileNewParams struct {
384 // A [File](https://platform.openai.com/docs/api-reference/files) ID that the
385 // vector store should use. Useful for tools like `file_search` that can access
386 // files.
387 FileID string `json:"file_id,required"`
388 // Set of 16 key-value pairs that can be attached to an object. This can be useful
389 // for storing additional information about the object in a structured format, and
390 // querying for objects via API or the dashboard. Keys are strings with a maximum
391 // length of 64 characters. Values are strings with a maximum length of 512
392 // characters, booleans, or numbers.
393 Attributes map[string]VectorStoreFileNewParamsAttributeUnion `json:"attributes,omitzero"`
394 // The chunking strategy used to chunk the file(s). If not set, will use the `auto`
395 // strategy. Only applicable if `file_ids` is non-empty.
396 ChunkingStrategy FileChunkingStrategyParamUnion `json:"chunking_strategy,omitzero"`
397 paramObj
398}
399
400func (r VectorStoreFileNewParams) MarshalJSON() (data []byte, err error) {
401 type shadow VectorStoreFileNewParams
402 return param.MarshalObject(r, (*shadow)(&r))
403}
404func (r *VectorStoreFileNewParams) UnmarshalJSON(data []byte) error {
405 return apijson.UnmarshalRoot(data, r)
406}
407
408// Only one field can be non-zero.
409//
410// Use [param.IsOmitted] to confirm if a field is set.
411type VectorStoreFileNewParamsAttributeUnion struct {
412 OfString param.Opt[string] `json:",omitzero,inline"`
413 OfFloat param.Opt[float64] `json:",omitzero,inline"`
414 OfBool param.Opt[bool] `json:",omitzero,inline"`
415 paramUnion
416}
417
418func (u VectorStoreFileNewParamsAttributeUnion) MarshalJSON() ([]byte, error) {
419 return param.MarshalUnion(u, u.OfString, u.OfFloat, u.OfBool)
420}
421func (u *VectorStoreFileNewParamsAttributeUnion) UnmarshalJSON(data []byte) error {
422 return apijson.UnmarshalRoot(data, u)
423}
424
425func (u *VectorStoreFileNewParamsAttributeUnion) asAny() any {
426 if !param.IsOmitted(u.OfString) {
427 return &u.OfString.Value
428 } else if !param.IsOmitted(u.OfFloat) {
429 return &u.OfFloat.Value
430 } else if !param.IsOmitted(u.OfBool) {
431 return &u.OfBool.Value
432 }
433 return nil
434}
435
436type VectorStoreFileUpdateParams struct {
437 // Set of 16 key-value pairs that can be attached to an object. This can be useful
438 // for storing additional information about the object in a structured format, and
439 // querying for objects via API or the dashboard. Keys are strings with a maximum
440 // length of 64 characters. Values are strings with a maximum length of 512
441 // characters, booleans, or numbers.
442 Attributes map[string]VectorStoreFileUpdateParamsAttributeUnion `json:"attributes,omitzero,required"`
443 paramObj
444}
445
446func (r VectorStoreFileUpdateParams) MarshalJSON() (data []byte, err error) {
447 type shadow VectorStoreFileUpdateParams
448 return param.MarshalObject(r, (*shadow)(&r))
449}
450func (r *VectorStoreFileUpdateParams) UnmarshalJSON(data []byte) error {
451 return apijson.UnmarshalRoot(data, r)
452}
453
454// Only one field can be non-zero.
455//
456// Use [param.IsOmitted] to confirm if a field is set.
457type VectorStoreFileUpdateParamsAttributeUnion struct {
458 OfString param.Opt[string] `json:",omitzero,inline"`
459 OfFloat param.Opt[float64] `json:",omitzero,inline"`
460 OfBool param.Opt[bool] `json:",omitzero,inline"`
461 paramUnion
462}
463
464func (u VectorStoreFileUpdateParamsAttributeUnion) MarshalJSON() ([]byte, error) {
465 return param.MarshalUnion(u, u.OfString, u.OfFloat, u.OfBool)
466}
467func (u *VectorStoreFileUpdateParamsAttributeUnion) UnmarshalJSON(data []byte) error {
468 return apijson.UnmarshalRoot(data, u)
469}
470
471func (u *VectorStoreFileUpdateParamsAttributeUnion) asAny() any {
472 if !param.IsOmitted(u.OfString) {
473 return &u.OfString.Value
474 } else if !param.IsOmitted(u.OfFloat) {
475 return &u.OfFloat.Value
476 } else if !param.IsOmitted(u.OfBool) {
477 return &u.OfBool.Value
478 }
479 return nil
480}
481
482type VectorStoreFileListParams struct {
483 // A cursor for use in pagination. `after` is an object ID that defines your place
484 // in the list. For instance, if you make a list request and receive 100 objects,
485 // ending with obj_foo, your subsequent call can include after=obj_foo in order to
486 // fetch the next page of the list.
487 After param.Opt[string] `query:"after,omitzero" json:"-"`
488 // A cursor for use in pagination. `before` is an object ID that defines your place
489 // in the list. For instance, if you make a list request and receive 100 objects,
490 // starting with obj_foo, your subsequent call can include before=obj_foo in order
491 // to fetch the previous page of the list.
492 Before param.Opt[string] `query:"before,omitzero" json:"-"`
493 // A limit on the number of objects to be returned. Limit can range between 1 and
494 // 100, and the default is 20.
495 Limit param.Opt[int64] `query:"limit,omitzero" json:"-"`
496 // Filter by file status. One of `in_progress`, `completed`, `failed`, `cancelled`.
497 //
498 // Any of "in_progress", "completed", "failed", "cancelled".
499 Filter VectorStoreFileListParamsFilter `query:"filter,omitzero" json:"-"`
500 // Sort order by the `created_at` timestamp of the objects. `asc` for ascending
501 // order and `desc` for descending order.
502 //
503 // Any of "asc", "desc".
504 Order VectorStoreFileListParamsOrder `query:"order,omitzero" json:"-"`
505 paramObj
506}
507
508// URLQuery serializes [VectorStoreFileListParams]'s query parameters as
509// `url.Values`.
510func (r VectorStoreFileListParams) URLQuery() (v url.Values, err error) {
511 return apiquery.MarshalWithSettings(r, apiquery.QuerySettings{
512 ArrayFormat: apiquery.ArrayQueryFormatBrackets,
513 NestedFormat: apiquery.NestedQueryFormatBrackets,
514 })
515}
516
517// Filter by file status. One of `in_progress`, `completed`, `failed`, `cancelled`.
518type VectorStoreFileListParamsFilter string
519
520const (
521 VectorStoreFileListParamsFilterInProgress VectorStoreFileListParamsFilter = "in_progress"
522 VectorStoreFileListParamsFilterCompleted VectorStoreFileListParamsFilter = "completed"
523 VectorStoreFileListParamsFilterFailed VectorStoreFileListParamsFilter = "failed"
524 VectorStoreFileListParamsFilterCancelled VectorStoreFileListParamsFilter = "cancelled"
525)
526
527// Sort order by the `created_at` timestamp of the objects. `asc` for ascending
528// order and `desc` for descending order.
529type VectorStoreFileListParamsOrder string
530
531const (
532 VectorStoreFileListParamsOrderAsc VectorStoreFileListParamsOrder = "asc"
533 VectorStoreFileListParamsOrderDesc VectorStoreFileListParamsOrder = "desc"
534)