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