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

     1  // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
     2  
     3  package anthropic
     4  
     5  import (
     6  	"context"
     7  	"encoding/json"
     8  	"errors"
     9  	"fmt"
    10  	"net/http"
    11  	"net/url"
    12  	"slices"
    13  	"time"
    14  
    15  	"github.com/anthropics/anthropic-sdk-go/internal/apijson"
    16  	"github.com/anthropics/anthropic-sdk-go/internal/apiquery"
    17  	"github.com/anthropics/anthropic-sdk-go/internal/requestconfig"
    18  	"github.com/anthropics/anthropic-sdk-go/option"
    19  	"github.com/anthropics/anthropic-sdk-go/packages/jsonl"
    20  	"github.com/anthropics/anthropic-sdk-go/packages/pagination"
    21  	"github.com/anthropics/anthropic-sdk-go/packages/param"
    22  	"github.com/anthropics/anthropic-sdk-go/packages/respjson"
    23  	"github.com/anthropics/anthropic-sdk-go/shared"
    24  	"github.com/anthropics/anthropic-sdk-go/shared/constant"
    25  )
    26  
    27  // MessageBatchService contains methods and other services that help with
    28  // interacting 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 [NewMessageBatchService] method instead.
    33  type MessageBatchService struct {
    34  	Options []option.RequestOption
    35  }
    36  
    37  // NewMessageBatchService 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.
    40  func NewMessageBatchService(opts ...option.RequestOption) (r MessageBatchService) {
    41  	r = MessageBatchService{}
    42  	r.Options = opts
    43  	return
    44  }
    45  
    46  // Send a batch of Message creation requests.
    47  //
    48  // The Message Batches API can be used to process multiple Messages API requests at
    49  // once. Once a Message Batch is created, it begins processing immediately. Batches
    50  // can take up to 24 hours to complete.
    51  //
    52  // Learn more about the Message Batches API in our
    53  // [user guide](https://platform.claude.com/docs/en/build-with-claude/batch-processing)
    54  func (r *MessageBatchService) New(ctx context.Context, params MessageBatchNewParams, opts ...option.RequestOption) (res *MessageBatch, err error) {
    55  	if !param.IsOmitted(params.UserProfileID) {
    56  		opts = append(opts, option.WithHeader("anthropic-user-profile-id", fmt.Sprintf("%v", params.UserProfileID.Value)))
    57  	}
    58  	if !param.IsOmitted(params.WorkspaceID) {
    59  		opts = append(opts, option.WithHeader("anthropic-workspace-id", fmt.Sprintf("%v", params.WorkspaceID.Value)))
    60  	}
    61  	opts = slices.Concat(r.Options, opts)
    62  	path := "v1/messages/batches"
    63  	err = requestconfig.ExecuteNewRequest(ctx, http.MethodPost, path, params, &res, opts...)
    64  	return res, err
    65  }
    66  
    67  // This endpoint is idempotent and can be used to poll for Message Batch
    68  // completion. To access the results of a Message Batch, make a request to the
    69  // `results_url` field in the response.
    70  //
    71  // Learn more about the Message Batches API in our
    72  // [user guide](https://platform.claude.com/docs/en/build-with-claude/batch-processing)
    73  func (r *MessageBatchService) Get(ctx context.Context, messageBatchID string, query MessageBatchGetParams, opts ...option.RequestOption) (res *MessageBatch, err error) {
    74  	if !param.IsOmitted(query.WorkspaceID) {
    75  		opts = append(opts, option.WithHeader("anthropic-workspace-id", fmt.Sprintf("%v", query.WorkspaceID.Value)))
    76  	}
    77  	opts = slices.Concat(r.Options, opts)
    78  	if messageBatchID == "" {
    79  		err = errors.New("missing required message_batch_id parameter")
    80  		return nil, err
    81  	}
    82  	path := fmt.Sprintf("v1/messages/batches/%s", messageBatchID)
    83  	err = requestconfig.ExecuteNewRequest(ctx, http.MethodGet, path, nil, &res, opts...)
    84  	return res, err
    85  }
    86  
    87  // List all Message Batches within a Workspace. Most recently created batches are
    88  // returned first.
    89  //
    90  // Learn more about the Message Batches API in our
    91  // [user guide](https://platform.claude.com/docs/en/build-with-claude/batch-processing)
    92  func (r *MessageBatchService) List(ctx context.Context, params MessageBatchListParams, opts ...option.RequestOption) (res *pagination.Page[MessageBatch], err error) {
    93  	var raw *http.Response
    94  	if !param.IsOmitted(params.WorkspaceID) {
    95  		opts = append(opts, option.WithHeader("anthropic-workspace-id", fmt.Sprintf("%v", params.WorkspaceID.Value)))
    96  	}
    97  	opts = slices.Concat(r.Options, opts)
    98  	opts = append([]option.RequestOption{option.WithResponseInto(&raw)}, opts...)
    99  	path := "v1/messages/batches"
   100  	cfg, err := requestconfig.NewRequestConfig(ctx, http.MethodGet, path, params, &res, opts...)
   101  	if err != nil {
   102  		return nil, err
   103  	}
   104  	err = cfg.Execute()
   105  	if err != nil {
   106  		return nil, err
   107  	}
   108  	res.SetPageConfig(cfg, raw)
   109  	return res, nil
   110  }
   111  
   112  // List all Message Batches within a Workspace. Most recently created batches are
   113  // returned first.
   114  //
   115  // Learn more about the Message Batches API in our
   116  // [user guide](https://platform.claude.com/docs/en/build-with-claude/batch-processing)
   117  func (r *MessageBatchService) ListAutoPaging(ctx context.Context, params MessageBatchListParams, opts ...option.RequestOption) *pagination.PageAutoPager[MessageBatch] {
   118  	return pagination.NewPageAutoPager(r.List(ctx, params, opts...))
   119  }
   120  
   121  // Delete a Message Batch.
   122  //
   123  // Message Batches can only be deleted once they've finished processing. If you'd
   124  // like to delete an in-progress batch, you must first cancel it.
   125  //
   126  // Learn more about the Message Batches API in our
   127  // [user guide](https://platform.claude.com/docs/en/build-with-claude/batch-processing)
   128  func (r *MessageBatchService) Delete(ctx context.Context, messageBatchID string, body MessageBatchDeleteParams, opts ...option.RequestOption) (res *DeletedMessageBatch, err error) {
   129  	if !param.IsOmitted(body.WorkspaceID) {
   130  		opts = append(opts, option.WithHeader("anthropic-workspace-id", fmt.Sprintf("%v", body.WorkspaceID.Value)))
   131  	}
   132  	opts = slices.Concat(r.Options, opts)
   133  	if messageBatchID == "" {
   134  		err = errors.New("missing required message_batch_id parameter")
   135  		return nil, err
   136  	}
   137  	path := fmt.Sprintf("v1/messages/batches/%s", messageBatchID)
   138  	err = requestconfig.ExecuteNewRequest(ctx, http.MethodDelete, path, nil, &res, opts...)
   139  	return res, err
   140  }
   141  
   142  // Batches may be canceled any time before processing ends. Once cancellation is
   143  // initiated, the batch enters a `canceling` state, at which time the system may
   144  // complete any in-progress, non-interruptible requests before finalizing
   145  // cancellation.
   146  //
   147  // The number of canceled requests is specified in `request_counts`. To determine
   148  // which requests were canceled, check the individual results within the batch.
   149  // Note that cancellation may not result in any canceled requests if they were
   150  // non-interruptible.
   151  //
   152  // Learn more about the Message Batches API in our
   153  // [user guide](https://platform.claude.com/docs/en/build-with-claude/batch-processing)
   154  func (r *MessageBatchService) Cancel(ctx context.Context, messageBatchID string, body MessageBatchCancelParams, opts ...option.RequestOption) (res *MessageBatch, err error) {
   155  	if !param.IsOmitted(body.WorkspaceID) {
   156  		opts = append(opts, option.WithHeader("anthropic-workspace-id", fmt.Sprintf("%v", body.WorkspaceID.Value)))
   157  	}
   158  	opts = slices.Concat(r.Options, opts)
   159  	if messageBatchID == "" {
   160  		err = errors.New("missing required message_batch_id parameter")
   161  		return nil, err
   162  	}
   163  	path := fmt.Sprintf("v1/messages/batches/%s/cancel", messageBatchID)
   164  	err = requestconfig.ExecuteNewRequest(ctx, http.MethodPost, path, nil, &res, opts...)
   165  	return res, err
   166  }
   167  
   168  // Streams the results of a Message Batch as a `.jsonl` file.
   169  //
   170  // Each line in the file is a JSON object containing the result of a single request
   171  // in the Message Batch. Results are not guaranteed to be in the same order as
   172  // requests. Use the `custom_id` field to match results to requests.
   173  //
   174  // Learn more about the Message Batches API in our
   175  // [user guide](https://platform.claude.com/docs/en/build-with-claude/batch-processing)
   176  func (r *MessageBatchService) ResultsStreaming(ctx context.Context, messageBatchID string, query MessageBatchResultsParams, opts ...option.RequestOption) (stream *jsonl.Stream[MessageBatchIndividualResponse]) {
   177  	var (
   178  		raw *http.Response
   179  		err error
   180  	)
   181  	if !param.IsOmitted(query.WorkspaceID) {
   182  		opts = append(opts, option.WithHeader("anthropic-workspace-id", fmt.Sprintf("%v", query.WorkspaceID.Value)))
   183  	}
   184  	opts = slices.Concat(r.Options, opts)
   185  	opts = append([]option.RequestOption{option.WithHeader("Accept", "application/x-jsonl")}, opts...)
   186  	if messageBatchID == "" {
   187  		err = errors.New("missing required message_batch_id parameter")
   188  		return jsonl.NewStream[MessageBatchIndividualResponse](nil, err)
   189  	}
   190  	path := fmt.Sprintf("v1/messages/batches/%s/results", messageBatchID)
   191  	err = requestconfig.ExecuteNewRequest(ctx, http.MethodGet, path, nil, &raw, opts...)
   192  	return jsonl.NewStream[MessageBatchIndividualResponse](raw, err)
   193  }
   194  
   195  type DeletedMessageBatch struct {
   196  	// ID of the Message Batch.
   197  	ID string `json:"id" api:"required"`
   198  	// Deleted object type.
   199  	//
   200  	// For Message Batches, this is always `"message_batch_deleted"`.
   201  	Type constant.MessageBatchDeleted `json:"type" default:"message_batch_deleted"`
   202  	// JSON contains metadata for fields, check presence with [respjson.Field.Valid].
   203  	JSON struct {
   204  		ID          respjson.Field
   205  		Type        respjson.Field
   206  		ExtraFields map[string]respjson.Field
   207  		raw         string
   208  	} `json:"-"`
   209  }
   210  
   211  // Returns the unmodified JSON received from the API
   212  func (r DeletedMessageBatch) RawJSON() string { return r.JSON.raw }
   213  func (r *DeletedMessageBatch) UnmarshalJSON(data []byte) error {
   214  	return apijson.UnmarshalRoot(data, r)
   215  }
   216  
   217  type MessageBatch struct {
   218  	// Unique object identifier.
   219  	//
   220  	// The format and length of IDs may change over time.
   221  	ID string `json:"id" api:"required"`
   222  	// RFC 3339 datetime string representing the time at which the Message Batch was
   223  	// archived and its results became unavailable.
   224  	ArchivedAt time.Time `json:"archived_at" api:"required" format:"date-time"`
   225  	// RFC 3339 datetime string representing the time at which cancellation was
   226  	// initiated for the Message Batch. Specified only if cancellation was initiated.
   227  	CancelInitiatedAt time.Time `json:"cancel_initiated_at" api:"required" format:"date-time"`
   228  	// RFC 3339 datetime string representing the time at which the Message Batch was
   229  	// created.
   230  	CreatedAt time.Time `json:"created_at" api:"required" format:"date-time"`
   231  	// RFC 3339 datetime string representing the time at which processing for the
   232  	// Message Batch ended. Specified only once processing ends.
   233  	//
   234  	// Processing ends when every request in a Message Batch has either succeeded,
   235  	// errored, canceled, or expired.
   236  	EndedAt time.Time `json:"ended_at" api:"required" format:"date-time"`
   237  	// RFC 3339 datetime string representing the time at which the Message Batch will
   238  	// expire and end processing, which is 24 hours after creation.
   239  	ExpiresAt time.Time `json:"expires_at" api:"required" format:"date-time"`
   240  	// Processing status of the Message Batch.
   241  	//
   242  	// Any of "in_progress", "canceling", "ended".
   243  	ProcessingStatus MessageBatchProcessingStatus `json:"processing_status" api:"required"`
   244  	// Tallies requests within the Message Batch, categorized by their status.
   245  	//
   246  	// Requests start as `processing` and move to one of the other statuses only once
   247  	// processing of the entire batch ends. The sum of all values always matches the
   248  	// total number of requests in the batch.
   249  	RequestCounts MessageBatchRequestCounts `json:"request_counts" api:"required"`
   250  	// URL to a `.jsonl` file containing the results of the Message Batch requests.
   251  	// Specified only once processing ends.
   252  	//
   253  	// Results in the file are not guaranteed to be in the same order as requests. Use
   254  	// the `custom_id` field to match results to requests.
   255  	ResultsURL string `json:"results_url" api:"required"`
   256  	// Object type.
   257  	//
   258  	// For Message Batches, this is always `"message_batch"`.
   259  	Type constant.MessageBatch `json:"type" default:"message_batch"`
   260  	// JSON contains metadata for fields, check presence with [respjson.Field.Valid].
   261  	JSON struct {
   262  		ID                respjson.Field
   263  		ArchivedAt        respjson.Field
   264  		CancelInitiatedAt respjson.Field
   265  		CreatedAt         respjson.Field
   266  		EndedAt           respjson.Field
   267  		ExpiresAt         respjson.Field
   268  		ProcessingStatus  respjson.Field
   269  		RequestCounts     respjson.Field
   270  		ResultsURL        respjson.Field
   271  		Type              respjson.Field
   272  		ExtraFields       map[string]respjson.Field
   273  		raw               string
   274  	} `json:"-"`
   275  }
   276  
   277  // Returns the unmodified JSON received from the API
   278  func (r MessageBatch) RawJSON() string { return r.JSON.raw }
   279  func (r *MessageBatch) UnmarshalJSON(data []byte) error {
   280  	return apijson.UnmarshalRoot(data, r)
   281  }
   282  
   283  // Processing status of the Message Batch.
   284  type MessageBatchProcessingStatus string
   285  
   286  const (
   287  	MessageBatchProcessingStatusInProgress MessageBatchProcessingStatus = "in_progress"
   288  	MessageBatchProcessingStatusCanceling  MessageBatchProcessingStatus = "canceling"
   289  	MessageBatchProcessingStatusEnded      MessageBatchProcessingStatus = "ended"
   290  )
   291  
   292  type MessageBatchCanceledResult struct {
   293  	Type constant.Canceled `json:"type" default:"canceled"`
   294  	// JSON contains metadata for fields, check presence with [respjson.Field.Valid].
   295  	JSON struct {
   296  		Type        respjson.Field
   297  		ExtraFields map[string]respjson.Field
   298  		raw         string
   299  	} `json:"-"`
   300  }
   301  
   302  // Returns the unmodified JSON received from the API
   303  func (r MessageBatchCanceledResult) RawJSON() string { return r.JSON.raw }
   304  func (r *MessageBatchCanceledResult) UnmarshalJSON(data []byte) error {
   305  	return apijson.UnmarshalRoot(data, r)
   306  }
   307  
   308  type MessageBatchErroredResult struct {
   309  	Error shared.ErrorResponse `json:"error" api:"required"`
   310  	Type  constant.Errored     `json:"type" default:"errored"`
   311  	// JSON contains metadata for fields, check presence with [respjson.Field.Valid].
   312  	JSON struct {
   313  		Error       respjson.Field
   314  		Type        respjson.Field
   315  		ExtraFields map[string]respjson.Field
   316  		raw         string
   317  	} `json:"-"`
   318  }
   319  
   320  // Returns the unmodified JSON received from the API
   321  func (r MessageBatchErroredResult) RawJSON() string { return r.JSON.raw }
   322  func (r *MessageBatchErroredResult) UnmarshalJSON(data []byte) error {
   323  	return apijson.UnmarshalRoot(data, r)
   324  }
   325  
   326  type MessageBatchExpiredResult struct {
   327  	Type constant.Expired `json:"type" default:"expired"`
   328  	// JSON contains metadata for fields, check presence with [respjson.Field.Valid].
   329  	JSON struct {
   330  		Type        respjson.Field
   331  		ExtraFields map[string]respjson.Field
   332  		raw         string
   333  	} `json:"-"`
   334  }
   335  
   336  // Returns the unmodified JSON received from the API
   337  func (r MessageBatchExpiredResult) RawJSON() string { return r.JSON.raw }
   338  func (r *MessageBatchExpiredResult) UnmarshalJSON(data []byte) error {
   339  	return apijson.UnmarshalRoot(data, r)
   340  }
   341  
   342  // This is a single line in the response `.jsonl` file and does not represent the
   343  // response as a whole.
   344  type MessageBatchIndividualResponse struct {
   345  	// Developer-provided ID created for each request in a Message Batch. Useful for
   346  	// matching results to requests, as results may be given out of request order.
   347  	//
   348  	// Must be unique for each request within the Message Batch.
   349  	CustomID string `json:"custom_id" api:"required"`
   350  	// Processing result for this request.
   351  	//
   352  	// Contains a Message output if processing was successful, an error response if
   353  	// processing failed, or the reason why processing was not attempted, such as
   354  	// cancellation or expiration.
   355  	Result MessageBatchResultUnion `json:"result" api:"required"`
   356  	// JSON contains metadata for fields, check presence with [respjson.Field.Valid].
   357  	JSON struct {
   358  		CustomID    respjson.Field
   359  		Result      respjson.Field
   360  		ExtraFields map[string]respjson.Field
   361  		raw         string
   362  	} `json:"-"`
   363  }
   364  
   365  // Returns the unmodified JSON received from the API
   366  func (r MessageBatchIndividualResponse) RawJSON() string { return r.JSON.raw }
   367  func (r *MessageBatchIndividualResponse) UnmarshalJSON(data []byte) error {
   368  	return apijson.UnmarshalRoot(data, r)
   369  }
   370  
   371  type MessageBatchRequestCounts struct {
   372  	// Number of requests in the Message Batch that have been canceled.
   373  	//
   374  	// This is zero until processing of the entire Message Batch has ended.
   375  	Canceled int64 `json:"canceled" api:"required"`
   376  	// Number of requests in the Message Batch that encountered an error.
   377  	//
   378  	// This is zero until processing of the entire Message Batch has ended.
   379  	Errored int64 `json:"errored" api:"required"`
   380  	// Number of requests in the Message Batch that have expired.
   381  	//
   382  	// This is zero until processing of the entire Message Batch has ended.
   383  	Expired int64 `json:"expired" api:"required"`
   384  	// Number of requests in the Message Batch that are processing.
   385  	Processing int64 `json:"processing" api:"required"`
   386  	// Number of requests in the Message Batch that have completed successfully.
   387  	//
   388  	// This is zero until processing of the entire Message Batch has ended.
   389  	Succeeded int64 `json:"succeeded" api:"required"`
   390  	// JSON contains metadata for fields, check presence with [respjson.Field.Valid].
   391  	JSON struct {
   392  		Canceled    respjson.Field
   393  		Errored     respjson.Field
   394  		Expired     respjson.Field
   395  		Processing  respjson.Field
   396  		Succeeded   respjson.Field
   397  		ExtraFields map[string]respjson.Field
   398  		raw         string
   399  	} `json:"-"`
   400  }
   401  
   402  // Returns the unmodified JSON received from the API
   403  func (r MessageBatchRequestCounts) RawJSON() string { return r.JSON.raw }
   404  func (r *MessageBatchRequestCounts) UnmarshalJSON(data []byte) error {
   405  	return apijson.UnmarshalRoot(data, r)
   406  }
   407  
   408  // MessageBatchResultUnion contains all possible properties and values from
   409  // [MessageBatchSucceededResult], [MessageBatchErroredResult],
   410  // [MessageBatchCanceledResult], [MessageBatchExpiredResult].
   411  //
   412  // Use the [MessageBatchResultUnion.AsAny] method to switch on the variant.
   413  //
   414  // Use the methods beginning with 'As' to cast the union to one of its variants.
   415  type MessageBatchResultUnion struct {
   416  	// This field is from variant [MessageBatchSucceededResult].
   417  	Message Message `json:"message"`
   418  	// Any of "succeeded", "errored", "canceled", "expired".
   419  	Type string `json:"type"`
   420  	// This field is from variant [MessageBatchErroredResult].
   421  	Error shared.ErrorResponse `json:"error"`
   422  	JSON  struct {
   423  		Message respjson.Field
   424  		Type    respjson.Field
   425  		Error   respjson.Field
   426  		raw     string
   427  	} `json:"-"`
   428  }
   429  
   430  // anyMessageBatchResult is implemented by each variant of
   431  // [MessageBatchResultUnion] to add type safety for the return type of
   432  // [MessageBatchResultUnion.AsAny]
   433  type anyMessageBatchResult interface {
   434  	implMessageBatchResultUnion()
   435  }
   436  
   437  func (MessageBatchSucceededResult) implMessageBatchResultUnion() {}
   438  func (MessageBatchErroredResult) implMessageBatchResultUnion()   {}
   439  func (MessageBatchCanceledResult) implMessageBatchResultUnion()  {}
   440  func (MessageBatchExpiredResult) implMessageBatchResultUnion()   {}
   441  
   442  // Use the following switch statement to find the correct variant
   443  //
   444  //	switch variant := MessageBatchResultUnion.AsAny().(type) {
   445  //	case anthropic.MessageBatchSucceededResult:
   446  //	case anthropic.MessageBatchErroredResult:
   447  //	case anthropic.MessageBatchCanceledResult:
   448  //	case anthropic.MessageBatchExpiredResult:
   449  //	default:
   450  //	  fmt.Errorf("no variant present")
   451  //	}
   452  func (u MessageBatchResultUnion) AsAny() anyMessageBatchResult {
   453  	switch u.Type {
   454  	case "succeeded":
   455  		return u.AsSucceeded()
   456  	case "errored":
   457  		return u.AsErrored()
   458  	case "canceled":
   459  		return u.AsCanceled()
   460  	case "expired":
   461  		return u.AsExpired()
   462  	}
   463  	return nil
   464  }
   465  
   466  func (u MessageBatchResultUnion) AsSucceeded() (v MessageBatchSucceededResult) {
   467  	apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v)
   468  	return
   469  }
   470  
   471  func (u MessageBatchResultUnion) AsErrored() (v MessageBatchErroredResult) {
   472  	apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v)
   473  	return
   474  }
   475  
   476  func (u MessageBatchResultUnion) AsCanceled() (v MessageBatchCanceledResult) {
   477  	apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v)
   478  	return
   479  }
   480  
   481  func (u MessageBatchResultUnion) AsExpired() (v MessageBatchExpiredResult) {
   482  	apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v)
   483  	return
   484  }
   485  
   486  // Returns the unmodified JSON received from the API
   487  func (u MessageBatchResultUnion) RawJSON() string { return u.JSON.raw }
   488  
   489  func (r *MessageBatchResultUnion) UnmarshalJSON(data []byte) error {
   490  	return apijson.UnmarshalRoot(data, r)
   491  }
   492  
   493  type MessageBatchSucceededResult struct {
   494  	Message Message            `json:"message" api:"required"`
   495  	Type    constant.Succeeded `json:"type" default:"succeeded"`
   496  	// JSON contains metadata for fields, check presence with [respjson.Field.Valid].
   497  	JSON struct {
   498  		Message     respjson.Field
   499  		Type        respjson.Field
   500  		ExtraFields map[string]respjson.Field
   501  		raw         string
   502  	} `json:"-"`
   503  }
   504  
   505  // Returns the unmodified JSON received from the API
   506  func (r MessageBatchSucceededResult) RawJSON() string { return r.JSON.raw }
   507  func (r *MessageBatchSucceededResult) UnmarshalJSON(data []byte) error {
   508  	return apijson.UnmarshalRoot(data, r)
   509  }
   510  
   511  type MessageBatchNewParams struct {
   512  	// List of requests for prompt completion. Each is an individual request to create
   513  	// a Message.
   514  	Requests []MessageBatchNewParamsRequest `json:"requests,omitzero" api:"required"`
   515  	// The user profile ID to attribute the requests in this batch to. Use when acting
   516  	// on behalf of a party other than your organization. Requires the `user-profiles`
   517  	// beta header. Applies to every request in the batch; an individual request whose
   518  	// `user_profile_id` body field conflicts with this header is errored.
   519  	UserProfileID param.Opt[string] `header:"anthropic-user-profile-id,omitzero" json:"-"`
   520  	WorkspaceID   param.Opt[string] `header:"anthropic-workspace-id,omitzero" json:"-"`
   521  	paramObj
   522  }
   523  
   524  func (r MessageBatchNewParams) MarshalJSON() (data []byte, err error) {
   525  	type shadow MessageBatchNewParams
   526  	return param.MarshalObject(r, (*shadow)(&r))
   527  }
   528  func (r *MessageBatchNewParams) UnmarshalJSON(data []byte) error {
   529  	return apijson.UnmarshalRoot(data, r)
   530  }
   531  
   532  // The properties CustomID, Params are required.
   533  type MessageBatchNewParamsRequest struct {
   534  	// Developer-provided ID created for each request in a Message Batch. Useful for
   535  	// matching results to requests, as results may be given out of request order.
   536  	//
   537  	// Must be unique for each request within the Message Batch.
   538  	CustomID string `json:"custom_id" api:"required"`
   539  	// Messages API creation parameters for the individual request.
   540  	//
   541  	// See the
   542  	// [Messages API reference](https://platform.claude.com/docs/en/api/messages) for
   543  	// full documentation on available parameters.
   544  	Params MessageBatchNewParamsRequestParams `json:"params,omitzero" api:"required"`
   545  	paramObj
   546  }
   547  
   548  func (r MessageBatchNewParamsRequest) MarshalJSON() (data []byte, err error) {
   549  	type shadow MessageBatchNewParamsRequest
   550  	return param.MarshalObject(r, (*shadow)(&r))
   551  }
   552  func (r *MessageBatchNewParamsRequest) UnmarshalJSON(data []byte) error {
   553  	return apijson.UnmarshalRoot(data, r)
   554  }
   555  
   556  // Messages API creation parameters for the individual request.
   557  //
   558  // See the
   559  // [Messages API reference](https://platform.claude.com/docs/en/api/messages) for
   560  // full documentation on available parameters.
   561  //
   562  // The properties MaxTokens, Messages, Model are required.
   563  type MessageBatchNewParamsRequestParams struct {
   564  	// The maximum number of tokens to generate before stopping.
   565  	//
   566  	// Note that our models may stop _before_ reaching this maximum. This parameter
   567  	// only specifies the absolute maximum number of tokens to generate.
   568  	//
   569  	// Set to `0` to populate the
   570  	// [prompt cache](https://platform.claude.com/docs/en/build-with-claude/prompt-caching#pre-warming-the-cache)
   571  	// without generating a response.
   572  	//
   573  	// Different models have different maximum values for this parameter. See
   574  	// [models](https://platform.claude.com/docs/en/about-claude/models/overview) for
   575  	// details.
   576  	MaxTokens int64 `json:"max_tokens" api:"required"`
   577  	// Input messages.
   578  	//
   579  	// Our models are trained to operate on alternating `user` and `assistant`
   580  	// conversational turns. When creating a new `Message`, you specify the prior
   581  	// conversational turns with the `messages` parameter, and the model then generates
   582  	// the next `Message` in the conversation. Consecutive `user` or `assistant` turns
   583  	// in your request will be combined into a single turn.
   584  	//
   585  	// Each input message must be an object with a `role` and `content`. You can
   586  	// specify a single `user`-role message, or you can include multiple `user` and
   587  	// `assistant` messages.
   588  	//
   589  	// If the final message uses the `assistant` role, the response content will
   590  	// continue immediately from the content in that message. This can be used to
   591  	// constrain part of the model's response.
   592  	//
   593  	// Example with a single `user` message:
   594  	//
   595  	// ```json
   596  	// [{ "role": "user", "content": "Hello, Claude" }]
   597  	// ```
   598  	//
   599  	// Example with multiple conversational turns:
   600  	//
   601  	// ```json
   602  	// [
   603  	//
   604  	//	{ "role": "user", "content": "Hello there." },
   605  	//	{ "role": "assistant", "content": "Hi, I'm Claude. How can I help you?" },
   606  	//	{ "role": "user", "content": "Can you explain LLMs in plain English?" }
   607  	//
   608  	// ]
   609  	// ```
   610  	//
   611  	// Example with a partially-filled response from Claude:
   612  	//
   613  	// ```json
   614  	// [
   615  	//
   616  	//	{
   617  	//	  "role": "user",
   618  	//	  "content": "What's the Greek name for Sun? (A) Sol (B) Helios (C) Sun"
   619  	//	},
   620  	//	{ "role": "assistant", "content": "The best answer is (" }
   621  	//
   622  	// ]
   623  	// ```
   624  	//
   625  	// Each input message `content` may be either a single `string` or an array of
   626  	// content blocks, where each block has a specific `type`. Using a `string` for
   627  	// `content` is shorthand for an array of one content block of type `"text"`. The
   628  	// following input messages are equivalent:
   629  	//
   630  	// ```json
   631  	// { "role": "user", "content": "Hello, Claude" }
   632  	// ```
   633  	//
   634  	// ```json
   635  	// { "role": "user", "content": [{ "type": "text", "text": "Hello, Claude" }] }
   636  	// ```
   637  	//
   638  	// See
   639  	// [input examples](https://platform.claude.com/docs/en/build-with-claude/working-with-messages).
   640  	//
   641  	// Note that if you want to include a
   642  	// [system prompt](https://platform.claude.com/docs/en/build-with-claude/prompt-engineering/claude-prompting-best-practices#give-claude-a-role),
   643  	// you can use the top-level `system` parameter — there is no `"system"` role for
   644  	// input messages in the Messages API.
   645  	//
   646  	// There is a limit of 100,000 messages in a single request.
   647  	Messages []MessageParam `json:"messages,omitzero" api:"required"`
   648  	// The model that will complete your prompt.
   649  	//
   650  	// See [models](https://docs.anthropic.com/en/docs/models-overview) for additional
   651  	// details and options.
   652  	Model Model `json:"model,omitzero" api:"required"`
   653  	// Specifies the geographic region for inference processing. If not specified, the
   654  	// workspace's `default_inference_geo` is used.
   655  	InferenceGeo param.Opt[string] `json:"inference_geo,omitzero"`
   656  	// Whether to incrementally stream the response using server-sent events.
   657  	//
   658  	// See [streaming](https://platform.claude.com/docs/en/build-with-claude/streaming)
   659  	// for details.
   660  	Stream param.Opt[bool] `json:"stream,omitzero"`
   661  	// Amount of randomness injected into the response.
   662  	//
   663  	// Defaults to `1.0`. Ranges from `0.0` to `1.0`. Use `temperature` closer to `0.0`
   664  	// for analytical / multiple choice, and closer to `1.0` for creative and
   665  	// generative tasks.
   666  	//
   667  	// Note that even with `temperature` of `0.0`, the results will not be fully
   668  	// deterministic.
   669  	//
   670  	// Deprecated: Deprecated. Models released after Claude Opus 4.6 do not support
   671  	// setting temperature. A value of 1.0 of will be accepted for backwards
   672  	// compatibility, all other values will be rejected with a 400 error.
   673  	Temperature param.Opt[float64] `json:"temperature,omitzero"`
   674  	// Only sample from the top K options for each subsequent token.
   675  	//
   676  	// Used to remove "long tail" low probability responses.
   677  	// [Learn more technical details here](https://towardsdatascience.com/how-to-sample-from-language-models-682bceb97277).
   678  	//
   679  	// Recommended for advanced use cases only.
   680  	//
   681  	// Deprecated: Deprecated. Models released after Claude Opus 4.6 do not accept
   682  	// top_k; any value will be rejected with a 400 error.
   683  	TopK param.Opt[int64] `json:"top_k,omitzero"`
   684  	// Use nucleus sampling.
   685  	//
   686  	// In nucleus sampling, we compute the cumulative distribution over all the options
   687  	// for each subsequent token in decreasing probability order and cut it off once it
   688  	// reaches a particular probability specified by `top_p`.
   689  	//
   690  	// Recommended for advanced use cases only.
   691  	//
   692  	// Deprecated: Deprecated. Models released after Claude Opus 4.6 do not support
   693  	// setting top_p. A value >= 0.99 will be accepted for backwards compatibility, all
   694  	// other values will be rejected with a 400 error.
   695  	TopP param.Opt[float64] `json:"top_p,omitzero"`
   696  	// Container identifier for reuse across requests.
   697  	Container MessageCreateParamsContainerUnion `json:"container,omitzero"`
   698  	// Top-level cache control automatically applies a cache_control marker to the last
   699  	// cacheable block in the request.
   700  	CacheControl CacheControlEphemeralParam `json:"cache_control,omitzero"`
   701  	// An object describing metadata about the request.
   702  	Metadata MetadataParam `json:"metadata,omitzero"`
   703  	// Configuration options for the model's output, such as the output format.
   704  	OutputConfig OutputConfigParam `json:"output_config,omitzero"`
   705  	// Determines whether to use priority capacity (if available) or standard capacity
   706  	// for this request.
   707  	//
   708  	// Anthropic offers different levels of service for your API requests. See
   709  	// [service-tiers](https://platform.claude.com/docs/en/api/service-tiers) for
   710  	// details.
   711  	//
   712  	// Any of "auto", "standard_only".
   713  	ServiceTier string `json:"service_tier,omitzero"`
   714  	// Custom text sequences that will cause the model to stop generating.
   715  	//
   716  	// Our models will normally stop when they have naturally completed their turn,
   717  	// which will result in a response `stop_reason` of `"end_turn"`.
   718  	//
   719  	// If you want the model to stop generating when it encounters custom strings of
   720  	// text, you can use the `stop_sequences` parameter. If the model encounters one of
   721  	// the custom sequences, the response `stop_reason` value will be `"stop_sequence"`
   722  	// and the response `stop_sequence` value will contain the matched stop sequence.
   723  	StopSequences []string `json:"stop_sequences,omitzero"`
   724  	// System prompt.
   725  	//
   726  	// A system prompt is a way of providing context and instructions to Claude, such
   727  	// as specifying a particular goal or role. See our
   728  	// [guide to system prompts](https://platform.claude.com/docs/en/build-with-claude/prompt-engineering/claude-prompting-best-practices#give-claude-a-role).
   729  	System []TextBlockParam `json:"system,omitzero"`
   730  	// Configuration for enabling Claude's extended thinking.
   731  	//
   732  	// When enabled, responses include `thinking` content blocks showing Claude's
   733  	// thinking process before the final answer. Requires a minimum budget of 1,024
   734  	// tokens and counts towards your `max_tokens` limit.
   735  	//
   736  	// See
   737  	// [extended thinking](https://platform.claude.com/docs/en/build-with-claude/extended-thinking)
   738  	// for details.
   739  	Thinking ThinkingConfigParamUnion `json:"thinking,omitzero"`
   740  	// How the model should use the provided tools. The model can use a specific tool,
   741  	// any available tool, decide by itself, or not use tools at all.
   742  	ToolChoice ToolChoiceUnionParam `json:"tool_choice,omitzero"`
   743  	// Definitions of tools that the model may use.
   744  	//
   745  	// If you include `tools` in your API request, the model may return `tool_use`
   746  	// content blocks that represent the model's use of those tools. You can then run
   747  	// those tools using the tool input generated by the model and then optionally
   748  	// return results back to the model using `tool_result` content blocks.
   749  	//
   750  	// There are two types of tools: **client tools** and **server tools**. The
   751  	// behavior described below applies to client tools. For
   752  	// [server tools](https://platform.claude.com/docs/en/agents-and-tools/tool-use/server-tools),
   753  	// see their individual documentation as each has its own behavior (e.g., the
   754  	// [web search tool](https://platform.claude.com/docs/en/agents-and-tools/tool-use/web-search-tool)).
   755  	//
   756  	// Each tool definition includes:
   757  	//
   758  	//   - `name`: Name of the tool.
   759  	//   - `description`: Optional, but strongly-recommended description of the tool.
   760  	//   - `input_schema`: [JSON schema](https://json-schema.org/draft/2020-12) for the
   761  	//     tool `input` shape that the model will produce in `tool_use` output content
   762  	//     blocks.
   763  	//
   764  	// For example, if you defined `tools` as:
   765  	//
   766  	// ```json
   767  	// [
   768  	//
   769  	//	{
   770  	//	  "name": "get_stock_price",
   771  	//	  "description": "Get the current stock price for a given ticker symbol.",
   772  	//	  "input_schema": {
   773  	//	    "type": "object",
   774  	//	    "properties": {
   775  	//	      "ticker": {
   776  	//	        "type": "string",
   777  	//	        "description": "The stock ticker symbol, e.g. AAPL for Apple Inc."
   778  	//	      }
   779  	//	    },
   780  	//	    "required": ["ticker"]
   781  	//	  }
   782  	//	}
   783  	//
   784  	// ]
   785  	// ```
   786  	//
   787  	// And then asked the model "What's the S&P 500 at today?", the model might produce
   788  	// `tool_use` content blocks in the response like this:
   789  	//
   790  	// ```json
   791  	// [
   792  	//
   793  	//	{
   794  	//	  "type": "tool_use",
   795  	//	  "id": "toolu_01D7FLrfh4GYq7yT1ULFeyMV",
   796  	//	  "name": "get_stock_price",
   797  	//	  "input": { "ticker": "^GSPC" }
   798  	//	}
   799  	//
   800  	// ]
   801  	// ```
   802  	//
   803  	// You might then run your `get_stock_price` tool with `{"ticker": "^GSPC"}` as an
   804  	// input, and return the following back to the model in a subsequent `user`
   805  	// message:
   806  	//
   807  	// ```json
   808  	// [
   809  	//
   810  	//	{
   811  	//	  "type": "tool_result",
   812  	//	  "tool_use_id": "toolu_01D7FLrfh4GYq7yT1ULFeyMV",
   813  	//	  "content": "259.75 USD"
   814  	//	}
   815  	//
   816  	// ]
   817  	// ```
   818  	//
   819  	// Tools can be used for workflows that include running client-side tools and
   820  	// functions, or more generally whenever you want the model to produce a particular
   821  	// JSON structure of output.
   822  	//
   823  	// See our
   824  	// [guide](https://platform.claude.com/docs/en/agents-and-tools/tool-use/overview)
   825  	// for more details.
   826  	Tools []ToolUnionParam `json:"tools,omitzero"`
   827  	paramObj
   828  }
   829  
   830  func (r MessageBatchNewParamsRequestParams) MarshalJSON() (data []byte, err error) {
   831  	type shadow MessageBatchNewParamsRequestParams
   832  	return param.MarshalObject(r, (*shadow)(&r))
   833  }
   834  func (r *MessageBatchNewParamsRequestParams) UnmarshalJSON(data []byte) error {
   835  	return apijson.UnmarshalRoot(data, r)
   836  }
   837  
   838  func init() {
   839  	apijson.RegisterFieldValidator[MessageBatchNewParamsRequestParams](
   840  		"service_tier", "auto", "standard_only",
   841  	)
   842  }
   843  
   844  type MessageBatchGetParams struct {
   845  	WorkspaceID param.Opt[string] `header:"anthropic-workspace-id,omitzero" json:"-"`
   846  	paramObj
   847  }
   848  
   849  type MessageBatchListParams struct {
   850  	// ID of the object to use as a cursor for pagination. When provided, returns the
   851  	// page of results immediately after this object.
   852  	AfterID param.Opt[string] `query:"after_id,omitzero" json:"-"`
   853  	// ID of the object to use as a cursor for pagination. When provided, returns the
   854  	// page of results immediately before this object.
   855  	BeforeID param.Opt[string] `query:"before_id,omitzero" json:"-"`
   856  	// Number of items to return per page.
   857  	//
   858  	// Defaults to `20`. Ranges from `1` to `1000`.
   859  	Limit       param.Opt[int64]  `query:"limit,omitzero" json:"-"`
   860  	WorkspaceID param.Opt[string] `header:"anthropic-workspace-id,omitzero" json:"-"`
   861  	paramObj
   862  }
   863  
   864  // URLQuery serializes [MessageBatchListParams]'s query parameters as `url.Values`.
   865  func (r MessageBatchListParams) URLQuery() (v url.Values, err error) {
   866  	return apiquery.MarshalWithSettings(r, apiquery.QuerySettings{
   867  		ArrayFormat:  apiquery.ArrayQueryFormatBrackets,
   868  		NestedFormat: apiquery.NestedQueryFormatBrackets,
   869  	})
   870  }
   871  
   872  type MessageBatchDeleteParams struct {
   873  	WorkspaceID param.Opt[string] `header:"anthropic-workspace-id,omitzero" json:"-"`
   874  	paramObj
   875  }
   876  
   877  type MessageBatchCancelParams struct {
   878  	WorkspaceID param.Opt[string] `header:"anthropic-workspace-id,omitzero" json:"-"`
   879  	paramObj
   880  }
   881  
   882  type MessageBatchResultsParams struct {
   883  	WorkspaceID param.Opt[string] `header:"anthropic-workspace-id,omitzero" json:"-"`
   884  	paramObj
   885  }