github.com/anthropics/anthropic-sdk-go@v1.70.1/betafile.go (about)

     1  // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
     2  
     3  package anthropic
     4  
     5  import (
     6  	"bytes"
     7  	"context"
     8  	"errors"
     9  	"fmt"
    10  	"io"
    11  	"mime/multipart"
    12  	"net/http"
    13  	"net/url"
    14  	"slices"
    15  	"time"
    16  
    17  	"github.com/anthropics/anthropic-sdk-go/internal/apiform"
    18  	"github.com/anthropics/anthropic-sdk-go/internal/apijson"
    19  	"github.com/anthropics/anthropic-sdk-go/internal/apiquery"
    20  	"github.com/anthropics/anthropic-sdk-go/internal/requestconfig"
    21  	"github.com/anthropics/anthropic-sdk-go/option"
    22  	"github.com/anthropics/anthropic-sdk-go/packages/pagination"
    23  	"github.com/anthropics/anthropic-sdk-go/packages/param"
    24  	"github.com/anthropics/anthropic-sdk-go/packages/respjson"
    25  	"github.com/anthropics/anthropic-sdk-go/shared/constant"
    26  )
    27  
    28  // BetaFileService contains methods and other services that help with interacting
    29  // with the anthropic API.
    30  //
    31  // Note, unlike clients, this service does not read variables from the environment
    32  // automatically. You should not instantiate this service directly, and instead use
    33  // the [NewBetaFileService] method instead.
    34  type BetaFileService struct {
    35  	Options []option.RequestOption
    36  }
    37  
    38  // NewBetaFileService 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.
    41  func NewBetaFileService(opts ...option.RequestOption) (r BetaFileService) {
    42  	r = BetaFileService{}
    43  	r.Options = opts
    44  	return
    45  }
    46  
    47  // List Files
    48  func (r *BetaFileService) List(ctx context.Context, params BetaFileListParams, opts ...option.RequestOption) (res *pagination.PageCursor[BetaFileMetadata], err error) {
    49  	var raw *http.Response
    50  	for _, v := range params.Betas {
    51  		opts = append(opts, option.WithHeaderAdd("anthropic-beta", fmt.Sprintf("%v", v)))
    52  	}
    53  	if !param.IsOmitted(params.WorkspaceID) {
    54  		opts = append(opts, option.WithHeader("anthropic-workspace-id", fmt.Sprintf("%v", params.WorkspaceID.Value)))
    55  	}
    56  	opts = slices.Concat(r.Options, opts)
    57  	opts = append([]option.RequestOption{option.WithResponseInto(&raw)}, opts...)
    58  	path := "v1/files?beta=true"
    59  	cfg, err := requestconfig.NewRequestConfig(ctx, http.MethodGet, path, params, &res, opts...)
    60  	if err != nil {
    61  		return nil, err
    62  	}
    63  	err = cfg.Execute()
    64  	if err != nil {
    65  		return nil, err
    66  	}
    67  	res.SetPageConfig(cfg, raw)
    68  	return res, nil
    69  }
    70  
    71  // List Files
    72  func (r *BetaFileService) ListAutoPaging(ctx context.Context, params BetaFileListParams, opts ...option.RequestOption) *pagination.PageCursorAutoPager[BetaFileMetadata] {
    73  	return pagination.NewPageCursorAutoPager(r.List(ctx, params, opts...))
    74  }
    75  
    76  // Delete File
    77  func (r *BetaFileService) Delete(ctx context.Context, fileID string, body BetaFileDeleteParams, opts ...option.RequestOption) (res *BetaDeletedFile, err error) {
    78  	for _, v := range body.Betas {
    79  		opts = append(opts, option.WithHeaderAdd("anthropic-beta", fmt.Sprintf("%v", v)))
    80  	}
    81  	if !param.IsOmitted(body.WorkspaceID) {
    82  		opts = append(opts, option.WithHeader("anthropic-workspace-id", fmt.Sprintf("%v", body.WorkspaceID.Value)))
    83  	}
    84  	opts = slices.Concat(r.Options, opts)
    85  	if fileID == "" {
    86  		err = errors.New("missing required file_id parameter")
    87  		return nil, err
    88  	}
    89  	path := fmt.Sprintf("v1/files/%s?beta=true", fileID)
    90  	err = requestconfig.ExecuteNewRequest(ctx, http.MethodDelete, path, nil, &res, opts...)
    91  	return res, err
    92  }
    93  
    94  // Download File
    95  func (r *BetaFileService) Download(ctx context.Context, fileID string, query BetaFileDownloadParams, opts ...option.RequestOption) (res *http.Response, err error) {
    96  	for _, v := range query.Betas {
    97  		opts = append(opts, option.WithHeaderAdd("anthropic-beta", fmt.Sprintf("%v", v)))
    98  	}
    99  	if !param.IsOmitted(query.WorkspaceID) {
   100  		opts = append(opts, option.WithHeader("anthropic-workspace-id", fmt.Sprintf("%v", query.WorkspaceID.Value)))
   101  	}
   102  	opts = slices.Concat(r.Options, opts)
   103  	opts = append([]option.RequestOption{option.WithHeader("Accept", "application/binary")}, opts...)
   104  	if fileID == "" {
   105  		err = errors.New("missing required file_id parameter")
   106  		return nil, err
   107  	}
   108  	path := fmt.Sprintf("v1/files/%s/content?beta=true", fileID)
   109  	err = requestconfig.ExecuteNewRequest(ctx, http.MethodGet, path, nil, &res, opts...)
   110  	return res, err
   111  }
   112  
   113  // Get File Metadata
   114  func (r *BetaFileService) GetMetadata(ctx context.Context, fileID string, query BetaFileGetMetadataParams, opts ...option.RequestOption) (res *BetaFileMetadata, err error) {
   115  	for _, v := range query.Betas {
   116  		opts = append(opts, option.WithHeaderAdd("anthropic-beta", fmt.Sprintf("%v", v)))
   117  	}
   118  	if !param.IsOmitted(query.WorkspaceID) {
   119  		opts = append(opts, option.WithHeader("anthropic-workspace-id", fmt.Sprintf("%v", query.WorkspaceID.Value)))
   120  	}
   121  	opts = slices.Concat(r.Options, opts)
   122  	if fileID == "" {
   123  		err = errors.New("missing required file_id parameter")
   124  		return nil, err
   125  	}
   126  	path := fmt.Sprintf("v1/files/%s?beta=true", fileID)
   127  	err = requestconfig.ExecuteNewRequest(ctx, http.MethodGet, path, nil, &res, opts...)
   128  	return res, err
   129  }
   130  
   131  // Upload File
   132  func (r *BetaFileService) Upload(ctx context.Context, params BetaFileUploadParams, opts ...option.RequestOption) (res *BetaFileMetadata, err error) {
   133  	for _, v := range params.Betas {
   134  		opts = append(opts, option.WithHeaderAdd("anthropic-beta", fmt.Sprintf("%v", v)))
   135  	}
   136  	if !param.IsOmitted(params.WorkspaceID) {
   137  		opts = append(opts, option.WithHeader("anthropic-workspace-id", fmt.Sprintf("%v", params.WorkspaceID.Value)))
   138  	}
   139  	opts = slices.Concat(r.Options, opts)
   140  	path := "v1/files?beta=true"
   141  	err = requestconfig.ExecuteNewRequest(ctx, http.MethodPost, path, params, &res, opts...)
   142  	return res, err
   143  }
   144  
   145  type BetaDeletedFile struct {
   146  	// ID of the deleted file.
   147  	ID string `json:"id" api:"required"`
   148  	// Deleted object type.
   149  	//
   150  	// For file deletion, this is always `"file_deleted"`.
   151  	//
   152  	// Any of "file_deleted".
   153  	Type BetaDeletedFileType `json:"type"`
   154  	// JSON contains metadata for fields, check presence with [respjson.Field.Valid].
   155  	JSON struct {
   156  		ID          respjson.Field
   157  		Type        respjson.Field
   158  		ExtraFields map[string]respjson.Field
   159  		raw         string
   160  	} `json:"-"`
   161  }
   162  
   163  // Returns the unmodified JSON received from the API
   164  func (r BetaDeletedFile) RawJSON() string { return r.JSON.raw }
   165  func (r *BetaDeletedFile) UnmarshalJSON(data []byte) error {
   166  	return apijson.UnmarshalRoot(data, r)
   167  }
   168  
   169  // Deleted object type.
   170  //
   171  // For file deletion, this is always `"file_deleted"`.
   172  type BetaDeletedFileType string
   173  
   174  const (
   175  	BetaDeletedFileTypeFileDeleted BetaDeletedFileType = "file_deleted"
   176  )
   177  
   178  type BetaFileMetadata struct {
   179  	// Unique object identifier.
   180  	//
   181  	// The format and length of IDs may change over time.
   182  	ID string `json:"id" api:"required"`
   183  	// RFC 3339 datetime string representing when the file was created.
   184  	CreatedAt time.Time `json:"created_at" api:"required" format:"date-time"`
   185  	// Original filename of the uploaded file.
   186  	Filename string `json:"filename" api:"required"`
   187  	// MIME type of the file.
   188  	MimeType string `json:"mime_type" api:"required"`
   189  	// Size of the file in bytes.
   190  	SizeBytes int64 `json:"size_bytes" api:"required"`
   191  	// Object type.
   192  	//
   193  	// For files, this is always `"file"`.
   194  	Type constant.File `json:"type" default:"file"`
   195  	// Whether the file can be downloaded.
   196  	Downloadable bool `json:"downloadable"`
   197  	// RFC 3339 datetime string representing when the file will expire and become
   198  	// unavailable for download. Null if the file does not expire. For files uploaded
   199  	// with `expires_in_seconds`, this is the upload time plus that value.
   200  	ExpiresAt time.Time `json:"expires_at" api:"nullable" format:"date-time"`
   201  	// The scope of this file, indicating the context in which it was created (e.g., a
   202  	// session).
   203  	Scope BetaFileScope `json:"scope" api:"nullable"`
   204  	// JSON contains metadata for fields, check presence with [respjson.Field.Valid].
   205  	JSON struct {
   206  		ID           respjson.Field
   207  		CreatedAt    respjson.Field
   208  		Filename     respjson.Field
   209  		MimeType     respjson.Field
   210  		SizeBytes    respjson.Field
   211  		Type         respjson.Field
   212  		Downloadable respjson.Field
   213  		ExpiresAt    respjson.Field
   214  		Scope        respjson.Field
   215  		ExtraFields  map[string]respjson.Field
   216  		raw          string
   217  	} `json:"-"`
   218  }
   219  
   220  // Returns the unmodified JSON received from the API
   221  func (r BetaFileMetadata) RawJSON() string { return r.JSON.raw }
   222  func (r *BetaFileMetadata) UnmarshalJSON(data []byte) error {
   223  	return apijson.UnmarshalRoot(data, r)
   224  }
   225  
   226  type BetaFileScope struct {
   227  	// The ID of the scoping resource (e.g., the session ID).
   228  	ID string `json:"id" api:"required"`
   229  	// The type of scope (e.g., `"session"`).
   230  	Type constant.Session `json:"type" default:"session"`
   231  	// JSON contains metadata for fields, check presence with [respjson.Field.Valid].
   232  	JSON struct {
   233  		ID          respjson.Field
   234  		Type        respjson.Field
   235  		ExtraFields map[string]respjson.Field
   236  		raw         string
   237  	} `json:"-"`
   238  }
   239  
   240  // Returns the unmodified JSON received from the API
   241  func (r BetaFileScope) RawJSON() string { return r.JSON.raw }
   242  func (r *BetaFileScope) UnmarshalJSON(data []byte) error {
   243  	return apijson.UnmarshalRoot(data, r)
   244  }
   245  
   246  type BetaFileListParams struct {
   247  	// Opaque page cursor returned in a prior list response's `next_page`. Prefixed
   248  	// `page_`.
   249  	Page param.Opt[string] `query:"page,omitzero" json:"-"`
   250  	// Number of items to return per page.
   251  	//
   252  	// Defaults to `20`. Ranges from `1` to `1000`.
   253  	Limit param.Opt[int64] `query:"limit,omitzero" json:"-"`
   254  	// Filter by scope ID. Only returns files associated with the specified scope
   255  	// (e.g., a session ID).
   256  	ScopeID     param.Opt[string] `query:"scope_id,omitzero" json:"-"`
   257  	WorkspaceID param.Opt[string] `header:"anthropic-workspace-id,omitzero" json:"-"`
   258  	// Restrict the result set to Files whose `id` is in this list. At most 100 entries
   259  	// (after de-duplication). Mutually exclusive with `page` and `limit`. When
   260  	// supplied, the response is always a single page (`next_page` is null). IDs that
   261  	// do not resolve to a visible File — including deleted Files — are silently
   262  	// omitted.
   263  	IDs []string `query:"ids,omitzero" json:"-"`
   264  	// Optional header to specify the beta version(s) you want to use.
   265  	Betas []AnthropicBeta `header:"anthropic-beta,omitzero" json:"-"`
   266  	paramObj
   267  }
   268  
   269  // URLQuery serializes [BetaFileListParams]'s query parameters as `url.Values`.
   270  func (r BetaFileListParams) URLQuery() (v url.Values, err error) {
   271  	return apiquery.MarshalWithSettings(r, apiquery.QuerySettings{
   272  		ArrayFormat:  apiquery.ArrayQueryFormatBrackets,
   273  		NestedFormat: apiquery.NestedQueryFormatBrackets,
   274  	})
   275  }
   276  
   277  type BetaFileDeleteParams struct {
   278  	WorkspaceID param.Opt[string] `header:"anthropic-workspace-id,omitzero" json:"-"`
   279  	// Optional header to specify the beta version(s) you want to use.
   280  	Betas []AnthropicBeta `header:"anthropic-beta,omitzero" json:"-"`
   281  	paramObj
   282  }
   283  
   284  type BetaFileDownloadParams struct {
   285  	WorkspaceID param.Opt[string] `header:"anthropic-workspace-id,omitzero" json:"-"`
   286  	// Optional header to specify the beta version(s) you want to use.
   287  	Betas []AnthropicBeta `header:"anthropic-beta,omitzero" json:"-"`
   288  	paramObj
   289  }
   290  
   291  type BetaFileGetMetadataParams struct {
   292  	WorkspaceID param.Opt[string] `header:"anthropic-workspace-id,omitzero" json:"-"`
   293  	// Optional header to specify the beta version(s) you want to use.
   294  	Betas []AnthropicBeta `header:"anthropic-beta,omitzero" json:"-"`
   295  	paramObj
   296  }
   297  
   298  type BetaFileUploadParams struct {
   299  	// The file to upload. Only the final path component of the part's `filename` is
   300  	// kept; an absent or empty `filename` is replaced with `unnamed` plus the
   301  	// extension for the file's stored `mime_type`, when known.
   302  	File io.Reader `json:"file,omitzero" api:"required" format:"binary"`
   303  	// Seconds from upload until the file expires and its bytes become permanently
   304  	// unavailable. Must be between 3600 (one hour) and 7776000 (ninety days).
   305  	ExpiresInSeconds param.Opt[int64]  `json:"expires_in_seconds,omitzero"`
   306  	WorkspaceID      param.Opt[string] `header:"anthropic-workspace-id,omitzero" json:"-"`
   307  	// Optional header to specify the beta version(s) you want to use.
   308  	Betas []AnthropicBeta `header:"anthropic-beta,omitzero" json:"-"`
   309  	paramObj
   310  }
   311  
   312  func (r BetaFileUploadParams) MarshalMultipart() (data []byte, contentType string, err error) {
   313  	buf := bytes.NewBuffer(nil)
   314  	writer := multipart.NewWriter(buf)
   315  	err = apiform.MarshalRoot(r, writer)
   316  	if err == nil {
   317  		err = apiform.WriteExtras(writer, r.ExtraFields())
   318  	}
   319  	if err != nil {
   320  		writer.Close()
   321  		return nil, "", err
   322  	}
   323  	err = writer.Close()
   324  	if err != nil {
   325  		return nil, "", err
   326  	}
   327  	return buf.Bytes(), writer.FormDataContentType(), nil
   328  }