vectorstore.go

  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	"reflect"
 13
 14	"github.com/openai/openai-go/internal/apijson"
 15	"github.com/openai/openai-go/internal/apiquery"
 16	"github.com/openai/openai-go/internal/requestconfig"
 17	"github.com/openai/openai-go/option"
 18	"github.com/openai/openai-go/packages/pagination"
 19	"github.com/openai/openai-go/packages/param"
 20	"github.com/openai/openai-go/packages/resp"
 21	"github.com/openai/openai-go/shared"
 22	"github.com/openai/openai-go/shared/constant"
 23	"github.com/tidwall/gjson"
 24)
 25
 26// VectorStoreService contains methods and other services that help with
 27// interacting with 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 [NewVectorStoreService] method instead.
 32type VectorStoreService struct {
 33	Options     []option.RequestOption
 34	Files       VectorStoreFileService
 35	FileBatches VectorStoreFileBatchService
 36}
 37
 38// NewVectorStoreService generates a new service that applies the given options to
 39// each request. These options are applied after the parent client's options (if
 40// there is one), and before any request-specific options.
 41func NewVectorStoreService(opts ...option.RequestOption) (r VectorStoreService) {
 42	r = VectorStoreService{}
 43	r.Options = opts
 44	r.Files = NewVectorStoreFileService(opts...)
 45	r.FileBatches = NewVectorStoreFileBatchService(opts...)
 46	return
 47}
 48
 49// Create a vector store.
 50func (r *VectorStoreService) New(ctx context.Context, body VectorStoreNewParams, opts ...option.RequestOption) (res *VectorStore, err error) {
 51	opts = append(r.Options[:], opts...)
 52	opts = append([]option.RequestOption{option.WithHeader("OpenAI-Beta", "assistants=v2")}, opts...)
 53	path := "vector_stores"
 54	err = requestconfig.ExecuteNewRequest(ctx, http.MethodPost, path, body, &res, opts...)
 55	return
 56}
 57
 58// Retrieves a vector store.
 59func (r *VectorStoreService) Get(ctx context.Context, vectorStoreID string, opts ...option.RequestOption) (res *VectorStore, err error) {
 60	opts = append(r.Options[:], opts...)
 61	opts = append([]option.RequestOption{option.WithHeader("OpenAI-Beta", "assistants=v2")}, opts...)
 62	if vectorStoreID == "" {
 63		err = errors.New("missing required vector_store_id parameter")
 64		return
 65	}
 66	path := fmt.Sprintf("vector_stores/%s", vectorStoreID)
 67	err = requestconfig.ExecuteNewRequest(ctx, http.MethodGet, path, nil, &res, opts...)
 68	return
 69}
 70
 71// Modifies a vector store.
 72func (r *VectorStoreService) Update(ctx context.Context, vectorStoreID string, body VectorStoreUpdateParams, opts ...option.RequestOption) (res *VectorStore, err error) {
 73	opts = append(r.Options[:], opts...)
 74	opts = append([]option.RequestOption{option.WithHeader("OpenAI-Beta", "assistants=v2")}, opts...)
 75	if vectorStoreID == "" {
 76		err = errors.New("missing required vector_store_id parameter")
 77		return
 78	}
 79	path := fmt.Sprintf("vector_stores/%s", vectorStoreID)
 80	err = requestconfig.ExecuteNewRequest(ctx, http.MethodPost, path, body, &res, opts...)
 81	return
 82}
 83
 84// Returns a list of vector stores.
 85func (r *VectorStoreService) List(ctx context.Context, query VectorStoreListParams, opts ...option.RequestOption) (res *pagination.CursorPage[VectorStore], err error) {
 86	var raw *http.Response
 87	opts = append(r.Options[:], opts...)
 88	opts = append([]option.RequestOption{option.WithHeader("OpenAI-Beta", "assistants=v2"), option.WithResponseInto(&raw)}, opts...)
 89	path := "vector_stores"
 90	cfg, err := requestconfig.NewRequestConfig(ctx, http.MethodGet, path, query, &res, opts...)
 91	if err != nil {
 92		return nil, err
 93	}
 94	err = cfg.Execute()
 95	if err != nil {
 96		return nil, err
 97	}
 98	res.SetPageConfig(cfg, raw)
 99	return res, nil
100}
101
102// Returns a list of vector stores.
103func (r *VectorStoreService) ListAutoPaging(ctx context.Context, query VectorStoreListParams, opts ...option.RequestOption) *pagination.CursorPageAutoPager[VectorStore] {
104	return pagination.NewCursorPageAutoPager(r.List(ctx, query, opts...))
105}
106
107// Delete a vector store.
108func (r *VectorStoreService) Delete(ctx context.Context, vectorStoreID string, opts ...option.RequestOption) (res *VectorStoreDeleted, err error) {
109	opts = append(r.Options[:], opts...)
110	opts = append([]option.RequestOption{option.WithHeader("OpenAI-Beta", "assistants=v2")}, opts...)
111	if vectorStoreID == "" {
112		err = errors.New("missing required vector_store_id parameter")
113		return
114	}
115	path := fmt.Sprintf("vector_stores/%s", vectorStoreID)
116	err = requestconfig.ExecuteNewRequest(ctx, http.MethodDelete, path, nil, &res, opts...)
117	return
118}
119
120// Search a vector store for relevant chunks based on a query and file attributes
121// filter.
122func (r *VectorStoreService) Search(ctx context.Context, vectorStoreID string, body VectorStoreSearchParams, opts ...option.RequestOption) (res *pagination.Page[VectorStoreSearchResponse], err error) {
123	var raw *http.Response
124	opts = append(r.Options[:], opts...)
125	opts = append([]option.RequestOption{option.WithHeader("OpenAI-Beta", "assistants=v2"), option.WithResponseInto(&raw)}, opts...)
126	if vectorStoreID == "" {
127		err = errors.New("missing required vector_store_id parameter")
128		return
129	}
130	path := fmt.Sprintf("vector_stores/%s/search", vectorStoreID)
131	cfg, err := requestconfig.NewRequestConfig(ctx, http.MethodPost, path, body, &res, opts...)
132	if err != nil {
133		return nil, err
134	}
135	err = cfg.Execute()
136	if err != nil {
137		return nil, err
138	}
139	res.SetPageConfig(cfg, raw)
140	return res, nil
141}
142
143// Search a vector store for relevant chunks based on a query and file attributes
144// filter.
145func (r *VectorStoreService) SearchAutoPaging(ctx context.Context, vectorStoreID string, body VectorStoreSearchParams, opts ...option.RequestOption) *pagination.PageAutoPager[VectorStoreSearchResponse] {
146	return pagination.NewPageAutoPager(r.Search(ctx, vectorStoreID, body, opts...))
147}
148
149// The default strategy. This strategy currently uses a `max_chunk_size_tokens` of
150// `800` and `chunk_overlap_tokens` of `400`.
151//
152// The property Type is required.
153type AutoFileChunkingStrategyParam struct {
154	// Always `auto`.
155	//
156	// This field can be elided, and will marshal its zero value as "auto".
157	Type constant.Auto `json:"type,required"`
158	paramObj
159}
160
161// IsPresent returns true if the field's value is not omitted and not the JSON
162// "null". To check if this field is omitted, use [param.IsOmitted].
163func (f AutoFileChunkingStrategyParam) IsPresent() bool { return !param.IsOmitted(f) && !f.IsNull() }
164func (r AutoFileChunkingStrategyParam) MarshalJSON() (data []byte, err error) {
165	type shadow AutoFileChunkingStrategyParam
166	return param.MarshalObject(r, (*shadow)(&r))
167}
168
169// FileChunkingStrategyUnion contains all possible properties and values from
170// [StaticFileChunkingStrategyObject], [OtherFileChunkingStrategyObject].
171//
172// Use the [FileChunkingStrategyUnion.AsAny] method to switch on the variant.
173//
174// Use the methods beginning with 'As' to cast the union to one of its variants.
175type FileChunkingStrategyUnion struct {
176	// This field is from variant [StaticFileChunkingStrategyObject].
177	Static StaticFileChunkingStrategy `json:"static"`
178	// Any of "static", "other".
179	Type string `json:"type"`
180	JSON struct {
181		Static resp.Field
182		Type   resp.Field
183		raw    string
184	} `json:"-"`
185}
186
187// Use the following switch statement to find the correct variant
188//
189//	switch variant := FileChunkingStrategyUnion.AsAny().(type) {
190//	case StaticFileChunkingStrategyObject:
191//	case OtherFileChunkingStrategyObject:
192//	default:
193//	  fmt.Errorf("no variant present")
194//	}
195func (u FileChunkingStrategyUnion) AsAny() any {
196	switch u.Type {
197	case "static":
198		return u.AsStatic()
199	case "other":
200		return u.AsOther()
201	}
202	return nil
203}
204
205func (u FileChunkingStrategyUnion) AsStatic() (v StaticFileChunkingStrategyObject) {
206	apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v)
207	return
208}
209
210func (u FileChunkingStrategyUnion) AsOther() (v OtherFileChunkingStrategyObject) {
211	apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v)
212	return
213}
214
215// Returns the unmodified JSON received from the API
216func (u FileChunkingStrategyUnion) RawJSON() string { return u.JSON.raw }
217
218func (r *FileChunkingStrategyUnion) UnmarshalJSON(data []byte) error {
219	return apijson.UnmarshalRoot(data, r)
220}
221
222func FileChunkingStrategyParamOfStatic(static StaticFileChunkingStrategyParam) FileChunkingStrategyParamUnion {
223	var variant StaticFileChunkingStrategyObjectParam
224	variant.Static = static
225	return FileChunkingStrategyParamUnion{OfStatic: &variant}
226}
227
228// Only one field can be non-zero.
229//
230// Use [param.IsOmitted] to confirm if a field is set.
231type FileChunkingStrategyParamUnion struct {
232	OfAuto   *AutoFileChunkingStrategyParam         `json:",omitzero,inline"`
233	OfStatic *StaticFileChunkingStrategyObjectParam `json:",omitzero,inline"`
234	paramUnion
235}
236
237// IsPresent returns true if the field's value is not omitted and not the JSON
238// "null". To check if this field is omitted, use [param.IsOmitted].
239func (u FileChunkingStrategyParamUnion) IsPresent() bool { return !param.IsOmitted(u) && !u.IsNull() }
240func (u FileChunkingStrategyParamUnion) MarshalJSON() ([]byte, error) {
241	return param.MarshalUnion[FileChunkingStrategyParamUnion](u.OfAuto, u.OfStatic)
242}
243
244func (u *FileChunkingStrategyParamUnion) asAny() any {
245	if !param.IsOmitted(u.OfAuto) {
246		return u.OfAuto
247	} else if !param.IsOmitted(u.OfStatic) {
248		return u.OfStatic
249	}
250	return nil
251}
252
253// Returns a pointer to the underlying variant's property, if present.
254func (u FileChunkingStrategyParamUnion) GetStatic() *StaticFileChunkingStrategyParam {
255	if vt := u.OfStatic; vt != nil {
256		return &vt.Static
257	}
258	return nil
259}
260
261// Returns a pointer to the underlying variant's property, if present.
262func (u FileChunkingStrategyParamUnion) GetType() *string {
263	if vt := u.OfAuto; vt != nil {
264		return (*string)(&vt.Type)
265	} else if vt := u.OfStatic; vt != nil {
266		return (*string)(&vt.Type)
267	}
268	return nil
269}
270
271func init() {
272	apijson.RegisterUnion[FileChunkingStrategyParamUnion](
273		"type",
274		apijson.UnionVariant{
275			TypeFilter:         gjson.JSON,
276			Type:               reflect.TypeOf(AutoFileChunkingStrategyParam{}),
277			DiscriminatorValue: "auto",
278		},
279		apijson.UnionVariant{
280			TypeFilter:         gjson.JSON,
281			Type:               reflect.TypeOf(StaticFileChunkingStrategyObjectParam{}),
282			DiscriminatorValue: "static",
283		},
284	)
285}
286
287// This is returned when the chunking strategy is unknown. Typically, this is
288// because the file was indexed before the `chunking_strategy` concept was
289// introduced in the API.
290type OtherFileChunkingStrategyObject struct {
291	// Always `other`.
292	Type constant.Other `json:"type,required"`
293	// Metadata for the response, check the presence of optional fields with the
294	// [resp.Field.IsPresent] method.
295	JSON struct {
296		Type        resp.Field
297		ExtraFields map[string]resp.Field
298		raw         string
299	} `json:"-"`
300}
301
302// Returns the unmodified JSON received from the API
303func (r OtherFileChunkingStrategyObject) RawJSON() string { return r.JSON.raw }
304func (r *OtherFileChunkingStrategyObject) UnmarshalJSON(data []byte) error {
305	return apijson.UnmarshalRoot(data, r)
306}
307
308type StaticFileChunkingStrategy struct {
309	// The number of tokens that overlap between chunks. The default value is `400`.
310	//
311	// Note that the overlap must not exceed half of `max_chunk_size_tokens`.
312	ChunkOverlapTokens int64 `json:"chunk_overlap_tokens,required"`
313	// The maximum number of tokens in each chunk. The default value is `800`. The
314	// minimum value is `100` and the maximum value is `4096`.
315	MaxChunkSizeTokens int64 `json:"max_chunk_size_tokens,required"`
316	// Metadata for the response, check the presence of optional fields with the
317	// [resp.Field.IsPresent] method.
318	JSON struct {
319		ChunkOverlapTokens resp.Field
320		MaxChunkSizeTokens resp.Field
321		ExtraFields        map[string]resp.Field
322		raw                string
323	} `json:"-"`
324}
325
326// Returns the unmodified JSON received from the API
327func (r StaticFileChunkingStrategy) RawJSON() string { return r.JSON.raw }
328func (r *StaticFileChunkingStrategy) UnmarshalJSON(data []byte) error {
329	return apijson.UnmarshalRoot(data, r)
330}
331
332// ToParam converts this StaticFileChunkingStrategy to a
333// StaticFileChunkingStrategyParam.
334//
335// Warning: the fields of the param type will not be present. ToParam should only
336// be used at the last possible moment before sending a request. Test for this with
337// StaticFileChunkingStrategyParam.IsOverridden()
338func (r StaticFileChunkingStrategy) ToParam() StaticFileChunkingStrategyParam {
339	return param.OverrideObj[StaticFileChunkingStrategyParam](r.RawJSON())
340}
341
342// The properties ChunkOverlapTokens, MaxChunkSizeTokens are required.
343type StaticFileChunkingStrategyParam struct {
344	// The number of tokens that overlap between chunks. The default value is `400`.
345	//
346	// Note that the overlap must not exceed half of `max_chunk_size_tokens`.
347	ChunkOverlapTokens int64 `json:"chunk_overlap_tokens,required"`
348	// The maximum number of tokens in each chunk. The default value is `800`. The
349	// minimum value is `100` and the maximum value is `4096`.
350	MaxChunkSizeTokens int64 `json:"max_chunk_size_tokens,required"`
351	paramObj
352}
353
354// IsPresent returns true if the field's value is not omitted and not the JSON
355// "null". To check if this field is omitted, use [param.IsOmitted].
356func (f StaticFileChunkingStrategyParam) IsPresent() bool { return !param.IsOmitted(f) && !f.IsNull() }
357func (r StaticFileChunkingStrategyParam) MarshalJSON() (data []byte, err error) {
358	type shadow StaticFileChunkingStrategyParam
359	return param.MarshalObject(r, (*shadow)(&r))
360}
361
362type StaticFileChunkingStrategyObject struct {
363	Static StaticFileChunkingStrategy `json:"static,required"`
364	// Always `static`.
365	Type constant.Static `json:"type,required"`
366	// Metadata for the response, check the presence of optional fields with the
367	// [resp.Field.IsPresent] method.
368	JSON struct {
369		Static      resp.Field
370		Type        resp.Field
371		ExtraFields map[string]resp.Field
372		raw         string
373	} `json:"-"`
374}
375
376// Returns the unmodified JSON received from the API
377func (r StaticFileChunkingStrategyObject) RawJSON() string { return r.JSON.raw }
378func (r *StaticFileChunkingStrategyObject) UnmarshalJSON(data []byte) error {
379	return apijson.UnmarshalRoot(data, r)
380}
381
382// Customize your own chunking strategy by setting chunk size and chunk overlap.
383//
384// The properties Static, Type are required.
385type StaticFileChunkingStrategyObjectParam struct {
386	Static StaticFileChunkingStrategyParam `json:"static,omitzero,required"`
387	// Always `static`.
388	//
389	// This field can be elided, and will marshal its zero value as "static".
390	Type constant.Static `json:"type,required"`
391	paramObj
392}
393
394// IsPresent returns true if the field's value is not omitted and not the JSON
395// "null". To check if this field is omitted, use [param.IsOmitted].
396func (f StaticFileChunkingStrategyObjectParam) IsPresent() bool {
397	return !param.IsOmitted(f) && !f.IsNull()
398}
399func (r StaticFileChunkingStrategyObjectParam) MarshalJSON() (data []byte, err error) {
400	type shadow StaticFileChunkingStrategyObjectParam
401	return param.MarshalObject(r, (*shadow)(&r))
402}
403
404// A vector store is a collection of processed files can be used by the
405// `file_search` tool.
406type VectorStore struct {
407	// The identifier, which can be referenced in API endpoints.
408	ID string `json:"id,required"`
409	// The Unix timestamp (in seconds) for when the vector store was created.
410	CreatedAt  int64                 `json:"created_at,required"`
411	FileCounts VectorStoreFileCounts `json:"file_counts,required"`
412	// The Unix timestamp (in seconds) for when the vector store was last active.
413	LastActiveAt int64 `json:"last_active_at,required"`
414	// Set of 16 key-value pairs that can be attached to an object. This can be useful
415	// for storing additional information about the object in a structured format, and
416	// querying for objects via API or the dashboard.
417	//
418	// Keys are strings with a maximum length of 64 characters. Values are strings with
419	// a maximum length of 512 characters.
420	Metadata shared.Metadata `json:"metadata,required"`
421	// The name of the vector store.
422	Name string `json:"name,required"`
423	// The object type, which is always `vector_store`.
424	Object constant.VectorStore `json:"object,required"`
425	// The status of the vector store, which can be either `expired`, `in_progress`, or
426	// `completed`. A status of `completed` indicates that the vector store is ready
427	// for use.
428	//
429	// Any of "expired", "in_progress", "completed".
430	Status VectorStoreStatus `json:"status,required"`
431	// The total number of bytes used by the files in the vector store.
432	UsageBytes int64 `json:"usage_bytes,required"`
433	// The expiration policy for a vector store.
434	ExpiresAfter VectorStoreExpiresAfter `json:"expires_after"`
435	// The Unix timestamp (in seconds) for when the vector store will expire.
436	ExpiresAt int64 `json:"expires_at,nullable"`
437	// Metadata for the response, check the presence of optional fields with the
438	// [resp.Field.IsPresent] method.
439	JSON struct {
440		ID           resp.Field
441		CreatedAt    resp.Field
442		FileCounts   resp.Field
443		LastActiveAt resp.Field
444		Metadata     resp.Field
445		Name         resp.Field
446		Object       resp.Field
447		Status       resp.Field
448		UsageBytes   resp.Field
449		ExpiresAfter resp.Field
450		ExpiresAt    resp.Field
451		ExtraFields  map[string]resp.Field
452		raw          string
453	} `json:"-"`
454}
455
456// Returns the unmodified JSON received from the API
457func (r VectorStore) RawJSON() string { return r.JSON.raw }
458func (r *VectorStore) UnmarshalJSON(data []byte) error {
459	return apijson.UnmarshalRoot(data, r)
460}
461
462type VectorStoreFileCounts struct {
463	// The number of files that were cancelled.
464	Cancelled int64 `json:"cancelled,required"`
465	// The number of files that have been successfully processed.
466	Completed int64 `json:"completed,required"`
467	// The number of files that have failed to process.
468	Failed int64 `json:"failed,required"`
469	// The number of files that are currently being processed.
470	InProgress int64 `json:"in_progress,required"`
471	// The total number of files.
472	Total int64 `json:"total,required"`
473	// Metadata for the response, check the presence of optional fields with the
474	// [resp.Field.IsPresent] method.
475	JSON struct {
476		Cancelled   resp.Field
477		Completed   resp.Field
478		Failed      resp.Field
479		InProgress  resp.Field
480		Total       resp.Field
481		ExtraFields map[string]resp.Field
482		raw         string
483	} `json:"-"`
484}
485
486// Returns the unmodified JSON received from the API
487func (r VectorStoreFileCounts) RawJSON() string { return r.JSON.raw }
488func (r *VectorStoreFileCounts) UnmarshalJSON(data []byte) error {
489	return apijson.UnmarshalRoot(data, r)
490}
491
492// The status of the vector store, which can be either `expired`, `in_progress`, or
493// `completed`. A status of `completed` indicates that the vector store is ready
494// for use.
495type VectorStoreStatus string
496
497const (
498	VectorStoreStatusExpired    VectorStoreStatus = "expired"
499	VectorStoreStatusInProgress VectorStoreStatus = "in_progress"
500	VectorStoreStatusCompleted  VectorStoreStatus = "completed"
501)
502
503// The expiration policy for a vector store.
504type VectorStoreExpiresAfter struct {
505	// Anchor timestamp after which the expiration policy applies. Supported anchors:
506	// `last_active_at`.
507	Anchor constant.LastActiveAt `json:"anchor,required"`
508	// The number of days after the anchor time that the vector store will expire.
509	Days int64 `json:"days,required"`
510	// Metadata for the response, check the presence of optional fields with the
511	// [resp.Field.IsPresent] method.
512	JSON struct {
513		Anchor      resp.Field
514		Days        resp.Field
515		ExtraFields map[string]resp.Field
516		raw         string
517	} `json:"-"`
518}
519
520// Returns the unmodified JSON received from the API
521func (r VectorStoreExpiresAfter) RawJSON() string { return r.JSON.raw }
522func (r *VectorStoreExpiresAfter) UnmarshalJSON(data []byte) error {
523	return apijson.UnmarshalRoot(data, r)
524}
525
526type VectorStoreDeleted struct {
527	ID      string                      `json:"id,required"`
528	Deleted bool                        `json:"deleted,required"`
529	Object  constant.VectorStoreDeleted `json:"object,required"`
530	// Metadata for the response, check the presence of optional fields with the
531	// [resp.Field.IsPresent] method.
532	JSON struct {
533		ID          resp.Field
534		Deleted     resp.Field
535		Object      resp.Field
536		ExtraFields map[string]resp.Field
537		raw         string
538	} `json:"-"`
539}
540
541// Returns the unmodified JSON received from the API
542func (r VectorStoreDeleted) RawJSON() string { return r.JSON.raw }
543func (r *VectorStoreDeleted) UnmarshalJSON(data []byte) error {
544	return apijson.UnmarshalRoot(data, r)
545}
546
547type VectorStoreSearchResponse struct {
548	// Set of 16 key-value pairs that can be attached to an object. This can be useful
549	// for storing additional information about the object in a structured format, and
550	// querying for objects via API or the dashboard. Keys are strings with a maximum
551	// length of 64 characters. Values are strings with a maximum length of 512
552	// characters, booleans, or numbers.
553	Attributes map[string]VectorStoreSearchResponseAttributeUnion `json:"attributes,required"`
554	// Content chunks from the file.
555	Content []VectorStoreSearchResponseContent `json:"content,required"`
556	// The ID of the vector store file.
557	FileID string `json:"file_id,required"`
558	// The name of the vector store file.
559	Filename string `json:"filename,required"`
560	// The similarity score for the result.
561	Score float64 `json:"score,required"`
562	// Metadata for the response, check the presence of optional fields with the
563	// [resp.Field.IsPresent] method.
564	JSON struct {
565		Attributes  resp.Field
566		Content     resp.Field
567		FileID      resp.Field
568		Filename    resp.Field
569		Score       resp.Field
570		ExtraFields map[string]resp.Field
571		raw         string
572	} `json:"-"`
573}
574
575// Returns the unmodified JSON received from the API
576func (r VectorStoreSearchResponse) RawJSON() string { return r.JSON.raw }
577func (r *VectorStoreSearchResponse) UnmarshalJSON(data []byte) error {
578	return apijson.UnmarshalRoot(data, r)
579}
580
581// VectorStoreSearchResponseAttributeUnion contains all possible properties and
582// values from [string], [float64], [bool].
583//
584// Use the methods beginning with 'As' to cast the union to one of its variants.
585//
586// If the underlying value is not a json object, one of the following properties
587// will be valid: OfString OfFloat OfBool]
588type VectorStoreSearchResponseAttributeUnion struct {
589	// This field will be present if the value is a [string] instead of an object.
590	OfString string `json:",inline"`
591	// This field will be present if the value is a [float64] instead of an object.
592	OfFloat float64 `json:",inline"`
593	// This field will be present if the value is a [bool] instead of an object.
594	OfBool bool `json:",inline"`
595	JSON   struct {
596		OfString resp.Field
597		OfFloat  resp.Field
598		OfBool   resp.Field
599		raw      string
600	} `json:"-"`
601}
602
603func (u VectorStoreSearchResponseAttributeUnion) AsString() (v string) {
604	apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v)
605	return
606}
607
608func (u VectorStoreSearchResponseAttributeUnion) AsFloat() (v float64) {
609	apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v)
610	return
611}
612
613func (u VectorStoreSearchResponseAttributeUnion) AsBool() (v bool) {
614	apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v)
615	return
616}
617
618// Returns the unmodified JSON received from the API
619func (u VectorStoreSearchResponseAttributeUnion) RawJSON() string { return u.JSON.raw }
620
621func (r *VectorStoreSearchResponseAttributeUnion) UnmarshalJSON(data []byte) error {
622	return apijson.UnmarshalRoot(data, r)
623}
624
625type VectorStoreSearchResponseContent struct {
626	// The text content returned from search.
627	Text string `json:"text,required"`
628	// The type of content.
629	//
630	// Any of "text".
631	Type string `json:"type,required"`
632	// Metadata for the response, check the presence of optional fields with the
633	// [resp.Field.IsPresent] method.
634	JSON struct {
635		Text        resp.Field
636		Type        resp.Field
637		ExtraFields map[string]resp.Field
638		raw         string
639	} `json:"-"`
640}
641
642// Returns the unmodified JSON received from the API
643func (r VectorStoreSearchResponseContent) RawJSON() string { return r.JSON.raw }
644func (r *VectorStoreSearchResponseContent) UnmarshalJSON(data []byte) error {
645	return apijson.UnmarshalRoot(data, r)
646}
647
648type VectorStoreNewParams struct {
649	// The name of the vector store.
650	Name param.Opt[string] `json:"name,omitzero"`
651	// Set of 16 key-value pairs that can be attached to an object. This can be useful
652	// for storing additional information about the object in a structured format, and
653	// querying for objects via API or the dashboard.
654	//
655	// Keys are strings with a maximum length of 64 characters. Values are strings with
656	// a maximum length of 512 characters.
657	Metadata shared.MetadataParam `json:"metadata,omitzero"`
658	// The chunking strategy used to chunk the file(s). If not set, will use the `auto`
659	// strategy. Only applicable if `file_ids` is non-empty.
660	ChunkingStrategy FileChunkingStrategyParamUnion `json:"chunking_strategy,omitzero"`
661	// The expiration policy for a vector store.
662	ExpiresAfter VectorStoreNewParamsExpiresAfter `json:"expires_after,omitzero"`
663	// A list of [File](https://platform.openai.com/docs/api-reference/files) IDs that
664	// the vector store should use. Useful for tools like `file_search` that can access
665	// files.
666	FileIDs []string `json:"file_ids,omitzero"`
667	paramObj
668}
669
670// IsPresent returns true if the field's value is not omitted and not the JSON
671// "null". To check if this field is omitted, use [param.IsOmitted].
672func (f VectorStoreNewParams) IsPresent() bool { return !param.IsOmitted(f) && !f.IsNull() }
673
674func (r VectorStoreNewParams) MarshalJSON() (data []byte, err error) {
675	type shadow VectorStoreNewParams
676	return param.MarshalObject(r, (*shadow)(&r))
677}
678
679// The expiration policy for a vector store.
680//
681// The properties Anchor, Days are required.
682type VectorStoreNewParamsExpiresAfter struct {
683	// The number of days after the anchor time that the vector store will expire.
684	Days int64 `json:"days,required"`
685	// Anchor timestamp after which the expiration policy applies. Supported anchors:
686	// `last_active_at`.
687	//
688	// This field can be elided, and will marshal its zero value as "last_active_at".
689	Anchor constant.LastActiveAt `json:"anchor,required"`
690	paramObj
691}
692
693// IsPresent returns true if the field's value is not omitted and not the JSON
694// "null". To check if this field is omitted, use [param.IsOmitted].
695func (f VectorStoreNewParamsExpiresAfter) IsPresent() bool { return !param.IsOmitted(f) && !f.IsNull() }
696func (r VectorStoreNewParamsExpiresAfter) MarshalJSON() (data []byte, err error) {
697	type shadow VectorStoreNewParamsExpiresAfter
698	return param.MarshalObject(r, (*shadow)(&r))
699}
700
701type VectorStoreUpdateParams struct {
702	// The name of the vector store.
703	Name param.Opt[string] `json:"name,omitzero"`
704	// The expiration policy for a vector store.
705	ExpiresAfter VectorStoreUpdateParamsExpiresAfter `json:"expires_after,omitzero"`
706	// Set of 16 key-value pairs that can be attached to an object. This can be useful
707	// for storing additional information about the object in a structured format, and
708	// querying for objects via API or the dashboard.
709	//
710	// Keys are strings with a maximum length of 64 characters. Values are strings with
711	// a maximum length of 512 characters.
712	Metadata shared.MetadataParam `json:"metadata,omitzero"`
713	paramObj
714}
715
716// IsPresent returns true if the field's value is not omitted and not the JSON
717// "null". To check if this field is omitted, use [param.IsOmitted].
718func (f VectorStoreUpdateParams) IsPresent() bool { return !param.IsOmitted(f) && !f.IsNull() }
719
720func (r VectorStoreUpdateParams) MarshalJSON() (data []byte, err error) {
721	type shadow VectorStoreUpdateParams
722	return param.MarshalObject(r, (*shadow)(&r))
723}
724
725// The expiration policy for a vector store.
726//
727// The properties Anchor, Days are required.
728type VectorStoreUpdateParamsExpiresAfter struct {
729	// The number of days after the anchor time that the vector store will expire.
730	Days int64 `json:"days,required"`
731	// Anchor timestamp after which the expiration policy applies. Supported anchors:
732	// `last_active_at`.
733	//
734	// This field can be elided, and will marshal its zero value as "last_active_at".
735	Anchor constant.LastActiveAt `json:"anchor,required"`
736	paramObj
737}
738
739// IsPresent returns true if the field's value is not omitted and not the JSON
740// "null". To check if this field is omitted, use [param.IsOmitted].
741func (f VectorStoreUpdateParamsExpiresAfter) IsPresent() bool {
742	return !param.IsOmitted(f) && !f.IsNull()
743}
744func (r VectorStoreUpdateParamsExpiresAfter) MarshalJSON() (data []byte, err error) {
745	type shadow VectorStoreUpdateParamsExpiresAfter
746	return param.MarshalObject(r, (*shadow)(&r))
747}
748
749type VectorStoreListParams struct {
750	// A cursor for use in pagination. `after` is an object ID that defines your place
751	// in the list. For instance, if you make a list request and receive 100 objects,
752	// ending with obj_foo, your subsequent call can include after=obj_foo in order to
753	// fetch the next page of the list.
754	After param.Opt[string] `query:"after,omitzero" json:"-"`
755	// A cursor for use in pagination. `before` is an object ID that defines your place
756	// in the list. For instance, if you make a list request and receive 100 objects,
757	// starting with obj_foo, your subsequent call can include before=obj_foo in order
758	// to fetch the previous page of the list.
759	Before param.Opt[string] `query:"before,omitzero" json:"-"`
760	// A limit on the number of objects to be returned. Limit can range between 1 and
761	// 100, and the default is 20.
762	Limit param.Opt[int64] `query:"limit,omitzero" json:"-"`
763	// Sort order by the `created_at` timestamp of the objects. `asc` for ascending
764	// order and `desc` for descending order.
765	//
766	// Any of "asc", "desc".
767	Order VectorStoreListParamsOrder `query:"order,omitzero" json:"-"`
768	paramObj
769}
770
771// IsPresent returns true if the field's value is not omitted and not the JSON
772// "null". To check if this field is omitted, use [param.IsOmitted].
773func (f VectorStoreListParams) IsPresent() bool { return !param.IsOmitted(f) && !f.IsNull() }
774
775// URLQuery serializes [VectorStoreListParams]'s query parameters as `url.Values`.
776func (r VectorStoreListParams) URLQuery() (v url.Values) {
777	return apiquery.MarshalWithSettings(r, apiquery.QuerySettings{
778		ArrayFormat:  apiquery.ArrayQueryFormatBrackets,
779		NestedFormat: apiquery.NestedQueryFormatBrackets,
780	})
781}
782
783// Sort order by the `created_at` timestamp of the objects. `asc` for ascending
784// order and `desc` for descending order.
785type VectorStoreListParamsOrder string
786
787const (
788	VectorStoreListParamsOrderAsc  VectorStoreListParamsOrder = "asc"
789	VectorStoreListParamsOrderDesc VectorStoreListParamsOrder = "desc"
790)
791
792type VectorStoreSearchParams struct {
793	// A query string for a search
794	Query VectorStoreSearchParamsQueryUnion `json:"query,omitzero,required"`
795	// The maximum number of results to return. This number should be between 1 and 50
796	// inclusive.
797	MaxNumResults param.Opt[int64] `json:"max_num_results,omitzero"`
798	// Whether to rewrite the natural language query for vector search.
799	RewriteQuery param.Opt[bool] `json:"rewrite_query,omitzero"`
800	// A filter to apply based on file attributes.
801	Filters VectorStoreSearchParamsFiltersUnion `json:"filters,omitzero"`
802	// Ranking options for search.
803	RankingOptions VectorStoreSearchParamsRankingOptions `json:"ranking_options,omitzero"`
804	paramObj
805}
806
807// IsPresent returns true if the field's value is not omitted and not the JSON
808// "null". To check if this field is omitted, use [param.IsOmitted].
809func (f VectorStoreSearchParams) IsPresent() bool { return !param.IsOmitted(f) && !f.IsNull() }
810
811func (r VectorStoreSearchParams) MarshalJSON() (data []byte, err error) {
812	type shadow VectorStoreSearchParams
813	return param.MarshalObject(r, (*shadow)(&r))
814}
815
816// Only one field can be non-zero.
817//
818// Use [param.IsOmitted] to confirm if a field is set.
819type VectorStoreSearchParamsQueryUnion struct {
820	OfString                       param.Opt[string] `json:",omitzero,inline"`
821	OfVectorStoreSearchsQueryArray []string          `json:",omitzero,inline"`
822	paramUnion
823}
824
825// IsPresent returns true if the field's value is not omitted and not the JSON
826// "null". To check if this field is omitted, use [param.IsOmitted].
827func (u VectorStoreSearchParamsQueryUnion) IsPresent() bool {
828	return !param.IsOmitted(u) && !u.IsNull()
829}
830func (u VectorStoreSearchParamsQueryUnion) MarshalJSON() ([]byte, error) {
831	return param.MarshalUnion[VectorStoreSearchParamsQueryUnion](u.OfString, u.OfVectorStoreSearchsQueryArray)
832}
833
834func (u *VectorStoreSearchParamsQueryUnion) asAny() any {
835	if !param.IsOmitted(u.OfString) {
836		return &u.OfString.Value
837	} else if !param.IsOmitted(u.OfVectorStoreSearchsQueryArray) {
838		return &u.OfVectorStoreSearchsQueryArray
839	}
840	return nil
841}
842
843// Only one field can be non-zero.
844//
845// Use [param.IsOmitted] to confirm if a field is set.
846type VectorStoreSearchParamsFiltersUnion struct {
847	OfComparisonFilter *shared.ComparisonFilterParam `json:",omitzero,inline"`
848	OfCompoundFilter   *shared.CompoundFilterParam   `json:",omitzero,inline"`
849	paramUnion
850}
851
852// IsPresent returns true if the field's value is not omitted and not the JSON
853// "null". To check if this field is omitted, use [param.IsOmitted].
854func (u VectorStoreSearchParamsFiltersUnion) IsPresent() bool {
855	return !param.IsOmitted(u) && !u.IsNull()
856}
857func (u VectorStoreSearchParamsFiltersUnion) MarshalJSON() ([]byte, error) {
858	return param.MarshalUnion[VectorStoreSearchParamsFiltersUnion](u.OfComparisonFilter, u.OfCompoundFilter)
859}
860
861func (u *VectorStoreSearchParamsFiltersUnion) asAny() any {
862	if !param.IsOmitted(u.OfComparisonFilter) {
863		return u.OfComparisonFilter
864	} else if !param.IsOmitted(u.OfCompoundFilter) {
865		return u.OfCompoundFilter
866	}
867	return nil
868}
869
870// Returns a pointer to the underlying variant's property, if present.
871func (u VectorStoreSearchParamsFiltersUnion) GetKey() *string {
872	if vt := u.OfComparisonFilter; vt != nil {
873		return &vt.Key
874	}
875	return nil
876}
877
878// Returns a pointer to the underlying variant's property, if present.
879func (u VectorStoreSearchParamsFiltersUnion) GetValue() *shared.ComparisonFilterValueUnionParam {
880	if vt := u.OfComparisonFilter; vt != nil {
881		return &vt.Value
882	}
883	return nil
884}
885
886// Returns a pointer to the underlying variant's property, if present.
887func (u VectorStoreSearchParamsFiltersUnion) GetFilters() []shared.ComparisonFilterParam {
888	if vt := u.OfCompoundFilter; vt != nil {
889		return vt.Filters
890	}
891	return nil
892}
893
894// Returns a pointer to the underlying variant's property, if present.
895func (u VectorStoreSearchParamsFiltersUnion) GetType() *string {
896	if vt := u.OfComparisonFilter; vt != nil {
897		return (*string)(&vt.Type)
898	} else if vt := u.OfCompoundFilter; vt != nil {
899		return (*string)(&vt.Type)
900	}
901	return nil
902}
903
904// Ranking options for search.
905type VectorStoreSearchParamsRankingOptions struct {
906	ScoreThreshold param.Opt[float64] `json:"score_threshold,omitzero"`
907	// Any of "auto", "default-2024-11-15".
908	Ranker string `json:"ranker,omitzero"`
909	paramObj
910}
911
912// IsPresent returns true if the field's value is not omitted and not the JSON
913// "null". To check if this field is omitted, use [param.IsOmitted].
914func (f VectorStoreSearchParamsRankingOptions) IsPresent() bool {
915	return !param.IsOmitted(f) && !f.IsNull()
916}
917func (r VectorStoreSearchParamsRankingOptions) MarshalJSON() (data []byte, err error) {
918	type shadow VectorStoreSearchParamsRankingOptions
919	return param.MarshalObject(r, (*shadow)(&r))
920}
921
922func init() {
923	apijson.RegisterFieldValidator[VectorStoreSearchParamsRankingOptions](
924		"Ranker", false, "auto", "default-2024-11-15",
925	)
926}