betafile.go

  1// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
  2
  3package anthropic
  4
  5import (
  6	"bytes"
  7	"context"
  8	"errors"
  9	"fmt"
 10	"io"
 11	"mime/multipart"
 12	"net/http"
 13	"net/url"
 14	"time"
 15
 16	"github.com/anthropics/anthropic-sdk-go/internal/apiform"
 17	"github.com/anthropics/anthropic-sdk-go/internal/apijson"
 18	"github.com/anthropics/anthropic-sdk-go/internal/apiquery"
 19	"github.com/anthropics/anthropic-sdk-go/internal/requestconfig"
 20	"github.com/anthropics/anthropic-sdk-go/option"
 21	"github.com/anthropics/anthropic-sdk-go/packages/pagination"
 22	"github.com/anthropics/anthropic-sdk-go/packages/param"
 23	"github.com/anthropics/anthropic-sdk-go/packages/respjson"
 24	"github.com/anthropics/anthropic-sdk-go/shared/constant"
 25)
 26
 27// BetaFileService contains methods and other services that help with interacting
 28// with the anthropic API.
 29//
 30// Note, unlike clients, this service does not read variables from the environment
 31// automatically. You should not instantiate this service directly, and instead use
 32// the [NewBetaFileService] method instead.
 33type BetaFileService struct {
 34	Options []option.RequestOption
 35}
 36
 37// NewBetaFileService generates a new service that applies the given options to
 38// each request. These options are applied after the parent client's options (if
 39// there is one), and before any request-specific options.
 40func NewBetaFileService(opts ...option.RequestOption) (r BetaFileService) {
 41	r = BetaFileService{}
 42	r.Options = opts
 43	return
 44}
 45
 46// List Files
 47func (r *BetaFileService) List(ctx context.Context, params BetaFileListParams, opts ...option.RequestOption) (res *pagination.Page[FileMetadata], err error) {
 48	var raw *http.Response
 49	for _, v := range params.Betas {
 50		opts = append(opts, option.WithHeaderAdd("anthropic-beta", fmt.Sprintf("%s", v)))
 51	}
 52	opts = append(r.Options[:], opts...)
 53	opts = append([]option.RequestOption{option.WithHeader("anthropic-beta", "files-api-2025-04-14"), option.WithResponseInto(&raw)}, opts...)
 54	path := "v1/files?beta=true"
 55	cfg, err := requestconfig.NewRequestConfig(ctx, http.MethodGet, path, params, &res, opts...)
 56	if err != nil {
 57		return nil, err
 58	}
 59	err = cfg.Execute()
 60	if err != nil {
 61		return nil, err
 62	}
 63	res.SetPageConfig(cfg, raw)
 64	return res, nil
 65}
 66
 67// List Files
 68func (r *BetaFileService) ListAutoPaging(ctx context.Context, params BetaFileListParams, opts ...option.RequestOption) *pagination.PageAutoPager[FileMetadata] {
 69	return pagination.NewPageAutoPager(r.List(ctx, params, opts...))
 70}
 71
 72// Delete File
 73func (r *BetaFileService) Delete(ctx context.Context, fileID string, body BetaFileDeleteParams, opts ...option.RequestOption) (res *DeletedFile, err error) {
 74	for _, v := range body.Betas {
 75		opts = append(opts, option.WithHeaderAdd("anthropic-beta", fmt.Sprintf("%s", v)))
 76	}
 77	opts = append(r.Options[:], opts...)
 78	opts = append([]option.RequestOption{option.WithHeader("anthropic-beta", "files-api-2025-04-14")}, opts...)
 79	if fileID == "" {
 80		err = errors.New("missing required file_id parameter")
 81		return
 82	}
 83	path := fmt.Sprintf("v1/files/%s?beta=true", fileID)
 84	err = requestconfig.ExecuteNewRequest(ctx, http.MethodDelete, path, nil, &res, opts...)
 85	return
 86}
 87
 88// Download File
 89func (r *BetaFileService) Download(ctx context.Context, fileID string, query BetaFileDownloadParams, opts ...option.RequestOption) (res *http.Response, err error) {
 90	for _, v := range query.Betas {
 91		opts = append(opts, option.WithHeaderAdd("anthropic-beta", fmt.Sprintf("%s", v)))
 92	}
 93	opts = append(r.Options[:], opts...)
 94	opts = append([]option.RequestOption{option.WithHeader("anthropic-beta", "files-api-2025-04-14"), option.WithHeader("Accept", "application/binary")}, opts...)
 95	if fileID == "" {
 96		err = errors.New("missing required file_id parameter")
 97		return
 98	}
 99	path := fmt.Sprintf("v1/files/%s/content?beta=true", fileID)
100	err = requestconfig.ExecuteNewRequest(ctx, http.MethodGet, path, nil, &res, opts...)
101	return
102}
103
104// Get File Metadata
105func (r *BetaFileService) GetMetadata(ctx context.Context, fileID string, query BetaFileGetMetadataParams, opts ...option.RequestOption) (res *FileMetadata, err error) {
106	for _, v := range query.Betas {
107		opts = append(opts, option.WithHeaderAdd("anthropic-beta", fmt.Sprintf("%s", v)))
108	}
109	opts = append(r.Options[:], opts...)
110	opts = append([]option.RequestOption{option.WithHeader("anthropic-beta", "files-api-2025-04-14")}, opts...)
111	if fileID == "" {
112		err = errors.New("missing required file_id parameter")
113		return
114	}
115	path := fmt.Sprintf("v1/files/%s?beta=true", fileID)
116	err = requestconfig.ExecuteNewRequest(ctx, http.MethodGet, path, nil, &res, opts...)
117	return
118}
119
120// Upload File
121func (r *BetaFileService) Upload(ctx context.Context, params BetaFileUploadParams, opts ...option.RequestOption) (res *FileMetadata, err error) {
122	for _, v := range params.Betas {
123		opts = append(opts, option.WithHeaderAdd("anthropic-beta", fmt.Sprintf("%s", v)))
124	}
125	opts = append(r.Options[:], opts...)
126	opts = append([]option.RequestOption{option.WithHeader("anthropic-beta", "files-api-2025-04-14")}, opts...)
127	path := "v1/files?beta=true"
128	err = requestconfig.ExecuteNewRequest(ctx, http.MethodPost, path, params, &res, opts...)
129	return
130}
131
132type DeletedFile struct {
133	// ID of the deleted file.
134	ID string `json:"id,required"`
135	// Deleted object type.
136	//
137	// For file deletion, this is always `"file_deleted"`.
138	//
139	// Any of "file_deleted".
140	Type DeletedFileType `json:"type"`
141	// JSON contains metadata for fields, check presence with [respjson.Field.Valid].
142	JSON struct {
143		ID          respjson.Field
144		Type        respjson.Field
145		ExtraFields map[string]respjson.Field
146		raw         string
147	} `json:"-"`
148}
149
150// Returns the unmodified JSON received from the API
151func (r DeletedFile) RawJSON() string { return r.JSON.raw }
152func (r *DeletedFile) UnmarshalJSON(data []byte) error {
153	return apijson.UnmarshalRoot(data, r)
154}
155
156// Deleted object type.
157//
158// For file deletion, this is always `"file_deleted"`.
159type DeletedFileType string
160
161const (
162	DeletedFileTypeFileDeleted DeletedFileType = "file_deleted"
163)
164
165type FileMetadata struct {
166	// Unique object identifier.
167	//
168	// The format and length of IDs may change over time.
169	ID string `json:"id,required"`
170	// RFC 3339 datetime string representing when the file was created.
171	CreatedAt time.Time `json:"created_at,required" format:"date-time"`
172	// Original filename of the uploaded file.
173	Filename string `json:"filename,required"`
174	// MIME type of the file.
175	MimeType string `json:"mime_type,required"`
176	// Size of the file in bytes.
177	SizeBytes int64 `json:"size_bytes,required"`
178	// Object type.
179	//
180	// For files, this is always `"file"`.
181	Type constant.File `json:"type,required"`
182	// Whether the file can be downloaded.
183	Downloadable bool `json:"downloadable"`
184	// JSON contains metadata for fields, check presence with [respjson.Field.Valid].
185	JSON struct {
186		ID           respjson.Field
187		CreatedAt    respjson.Field
188		Filename     respjson.Field
189		MimeType     respjson.Field
190		SizeBytes    respjson.Field
191		Type         respjson.Field
192		Downloadable respjson.Field
193		ExtraFields  map[string]respjson.Field
194		raw          string
195	} `json:"-"`
196}
197
198// Returns the unmodified JSON received from the API
199func (r FileMetadata) RawJSON() string { return r.JSON.raw }
200func (r *FileMetadata) UnmarshalJSON(data []byte) error {
201	return apijson.UnmarshalRoot(data, r)
202}
203
204type BetaFileListParams struct {
205	// ID of the object to use as a cursor for pagination. When provided, returns the
206	// page of results immediately after this object.
207	AfterID param.Opt[string] `query:"after_id,omitzero" json:"-"`
208	// ID of the object to use as a cursor for pagination. When provided, returns the
209	// page of results immediately before this object.
210	BeforeID param.Opt[string] `query:"before_id,omitzero" json:"-"`
211	// Number of items to return per page.
212	//
213	// Defaults to `20`. Ranges from `1` to `1000`.
214	Limit param.Opt[int64] `query:"limit,omitzero" json:"-"`
215	// Optional header to specify the beta version(s) you want to use.
216	Betas []AnthropicBeta `header:"anthropic-beta,omitzero" json:"-"`
217	paramObj
218}
219
220// URLQuery serializes [BetaFileListParams]'s query parameters as `url.Values`.
221func (r BetaFileListParams) URLQuery() (v url.Values, err error) {
222	return apiquery.MarshalWithSettings(r, apiquery.QuerySettings{
223		ArrayFormat:  apiquery.ArrayQueryFormatComma,
224		NestedFormat: apiquery.NestedQueryFormatBrackets,
225	})
226}
227
228type BetaFileDeleteParams struct {
229	// Optional header to specify the beta version(s) you want to use.
230	Betas []AnthropicBeta `header:"anthropic-beta,omitzero" json:"-"`
231	paramObj
232}
233
234type BetaFileDownloadParams struct {
235	// Optional header to specify the beta version(s) you want to use.
236	Betas []AnthropicBeta `header:"anthropic-beta,omitzero" json:"-"`
237	paramObj
238}
239
240type BetaFileGetMetadataParams struct {
241	// Optional header to specify the beta version(s) you want to use.
242	Betas []AnthropicBeta `header:"anthropic-beta,omitzero" json:"-"`
243	paramObj
244}
245
246type BetaFileUploadParams struct {
247	// The file to upload
248	File io.Reader `json:"file,omitzero,required" format:"binary"`
249	// Optional header to specify the beta version(s) you want to use.
250	Betas []AnthropicBeta `header:"anthropic-beta,omitzero" json:"-"`
251	paramObj
252}
253
254func (r BetaFileUploadParams) MarshalMultipart() (data []byte, contentType string, err error) {
255	buf := bytes.NewBuffer(nil)
256	writer := multipart.NewWriter(buf)
257	err = apiform.MarshalRoot(r, writer)
258	if err == nil {
259		err = apiform.WriteExtras(writer, r.ExtraFields())
260	}
261	if err != nil {
262		writer.Close()
263		return nil, "", err
264	}
265	err = writer.Close()
266	if err != nil {
267		return nil, "", err
268	}
269	return buf.Bytes(), writer.FormDataContentType(), nil
270}