diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 6ede0d7c..7a80ae49 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -13,6 +13,37 @@ on: - 'stl-preview-base/**' jobs: + build: + timeout-minutes: 10 + name: build + permissions: + contents: read + id-token: write + runs-on: ${{ github.repository == 'stainless-sdks/anthropic-go' && 'depot-ubuntu-24.04' || 'ubuntu-latest' }} + if: |- + github.repository == 'stainless-sdks/anthropic-go' && + (github.event_name == 'push' || github.event.pull_request.head.repo.fork) + steps: + - uses: actions/checkout@v6 + + - name: Get GitHub OIDC Token + if: |- + github.repository == 'stainless-sdks/anthropic-go' && + !startsWith(github.ref, 'refs/heads/stl/') + id: github-oidc + uses: actions/github-script@v8 + with: + script: core.setOutput('github_token', await core.getIDToken()); + + - name: Upload tarball + if: |- + github.repository == 'stainless-sdks/anthropic-go' && + !startsWith(github.ref, 'refs/heads/stl/') + env: + URL: https://pkg.stainless.com/s + AUTH: ${{ steps.github-oidc.outputs.github_token }} + SHA: ${{ github.sha }} + run: ./scripts/utils/upload-artifact.sh lint: timeout-minutes: 10 name: lint diff --git a/.release-please-manifest.json b/.release-please-manifest.json index f97891a6..c775f946 100644 --- a/.release-please-manifest.json +++ b/.release-please-manifest.json @@ -1,3 +1,3 @@ { - ".": "1.26.0" + ".": "1.27.0" } diff --git a/.stats.yml b/.stats.yml index be9d17c3..3336b3bc 100644 --- a/.stats.yml +++ b/.stats.yml @@ -1,4 +1,4 @@ configured_endpoints: 34 -openapi_spec_url: https://storage.googleapis.com/stainless-sdk-openapi-specs/anthropic%2Fanthropic-29a6b7ba51942cd606e5bf4b533e5aac1bef42f6d4b1f7f45f756304cf676782.yml -openapi_spec_hash: 58021ab18daccd5c45a930ffd7d6ab4d -config_hash: 4e204fead5f0af80eb9effa1d1e34dca +openapi_spec_url: https://storage.googleapis.com/stainless-sdk-openapi-specs/anthropic%2Fanthropic-7fce94a3c9f72c1d81df2009682a3b554e4b641b32443fd7c1f09f566420f711.yml +openapi_spec_hash: ae7e30bb8d093b5546cdc2b180f7b8e0 +config_hash: 32f037e4bc66dfaca12016b0e5110140 diff --git a/CHANGELOG.md b/CHANGELOG.md index 70f89c50..eaa63d95 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,41 @@ # Changelog +## 1.27.0 (2026-03-16) + +Full Changelog: [v1.26.0...v1.27.0](https://github.com/anthropics/anthropic-sdk-go/compare/v1.26.0...v1.27.0) + +### Features + +* **api:** change array_format to brackets ([ca5ae6e](https://github.com/anthropics/anthropic-sdk-go/commit/ca5ae6eaf8243aece877d33eb88653db2e439a36)) +* **api:** chore(config): clean up model enum list ([#31](https://github.com/anthropics/anthropic-sdk-go/issues/31)) ([1db4ea7](https://github.com/anthropics/anthropic-sdk-go/commit/1db4ea7956259bb217bc2523a5244b6029c4bd15)) +* **api:** GA thinking-display-setting ([1924af2](https://github.com/anthropics/anthropic-sdk-go/commit/1924af22e00fad68ccf31a3809c8cab8d442c048)) +* **api:** remove publishing section from cli target ([514282e](https://github.com/anthropics/anthropic-sdk-go/commit/514282e1728881f7ef4c6782f3000ca0ec632d53)) +* **tests:** update mock server ([cf24ced](https://github.com/anthropics/anthropic-sdk-go/commit/cf24ced2844da5d0f645e7a2afbabb936c891892)) + + +### Bug Fixes + +* allow canceling a request while it is waiting to retry ([32ee053](https://github.com/anthropics/anthropic-sdk-go/commit/32ee05317970d99df3147c65c2055efabe354472)) +* **client:** update model reference from claude-3-7-sonnet-latest to claude-sonnet-4-5 ([2f42e73](https://github.com/anthropics/anthropic-sdk-go/commit/2f42e7336295d898d18c66ddd6f9f70bab108cc6)) + + +### Chores + +* **client:** reorganize code in Messages files to lead to less conflicts ([c677bb5](https://github.com/anthropics/anthropic-sdk-go/commit/c677bb58a3da8f17f0dbc630b5b28faed995aa6b)) +* **internal:** codegen related update ([c978aac](https://github.com/anthropics/anthropic-sdk-go/commit/c978aacf53bbcf6555ba97bdc6bdfc9be9d8f98d)) +* **internal:** codegen related update ([4ac31a2](https://github.com/anthropics/anthropic-sdk-go/commit/4ac31a2fb9dc45a41bcbaa25dfbf8848119768ec)) +* **internal:** codegen related update ([5b2b2fa](https://github.com/anthropics/anthropic-sdk-go/commit/5b2b2fa276ad9365ddcb53270f307db05e5b6363)) +* **internal:** codegen related update ([9678c6c](https://github.com/anthropics/anthropic-sdk-go/commit/9678c6c5d375f66cb569a537a0766a5ed4d8f7f0)) +* **internal:** codegen related update ([f6035d2](https://github.com/anthropics/anthropic-sdk-go/commit/f6035d2bb0c50cf97cea78fb3fe854289b11a34c)) +* **internal:** codegen related update ([9246bbb](https://github.com/anthropics/anthropic-sdk-go/commit/9246bbb15553cee531b5caef2c7876e84a8fe8f2)) +* **internal:** move custom custom `json` tags to `api` ([4392627](https://github.com/anthropics/anthropic-sdk-go/commit/4392627107c43726c242923c16b0f5ac2b432082)) +* **tests:** unskip tests that are now supported in steady ([b0ca374](https://github.com/anthropics/anthropic-sdk-go/commit/b0ca37403486c65ae171d2b330ff82c938fe9b58)) + + +### Documentation + +* streamline README, centralize documentation at docs.anthropic.com ([33f6943](https://github.com/anthropics/anthropic-sdk-go/commit/33f69431abd96025134d8967c20a1f313af3382d)), closes [#587](https://github.com/anthropics/anthropic-sdk-go/issues/587) + ## 1.26.0 (2026-02-19) Full Changelog: [v1.25.1...v1.26.0](https://github.com/anthropics/anthropic-sdk-go/compare/v1.25.1...v1.26.0) diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index b34f0dd6..d63018a6 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -1,3 +1,7 @@ +## Contributing to documentation + +The documentation for this SDK lives at [platform.claude.com/docs/en/api/sdks/go](https://platform.claude.com/docs/en/api/sdks/go). To suggest changes, open an issue. + ## Setting up the environment To set up the repository, run: @@ -46,7 +50,7 @@ $ go mod edit -replace github.com/anthropics/anthropic-sdk-go=/path/to/anthropic ## Running tests -Most tests require you to [set up a mock server](https://github.com/stoplightio/prism) against the OpenAPI spec to run the tests. +Most tests require you to [set up a mock server](https://github.com/dgellow/steady) against the OpenAPI spec to run the tests. ```sh $ ./scripts/mock diff --git a/README.md b/README.md index 232bf611..a93fd351 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -# Anthropic Go API Library +# Claude SDK for Go @@ -6,8 +6,11 @@ -The Anthropic Go library provides convenient access to the [Anthropic REST API](https://docs.anthropic.com/claude/reference/) -from applications written in Go. +The Claude SDK for Go provides access to the [Claude API](https://docs.anthropic.com/en/api/) from Go applications. + +## Documentation + +Full documentation is available at **[platform.claude.com/docs/en/api/sdks/go](https://platform.claude.com/docs/en/api/sdks/go)**. ## Installation @@ -21,23 +24,17 @@ import ( -Or to pin the version: +Or explicitly add the dependency: ```sh -go get -u 'github.com/anthropics/anthropic-sdk-go@v1.26.0' +go get -u 'github.com/anthropics/anthropic-sdk-go@v1.27.0' ``` -## Requirements - -This library requires Go 1.22+. - -## Usage - -The full API of this library can be found in [api.md](api.md). +## Getting started ```go package main @@ -59,941 +56,23 @@ func main() { Messages: []anthropic.MessageParam{ anthropic.NewUserMessage(anthropic.NewTextBlock("What is a quaternion?")), }, - Model: anthropic.ModelClaudeSonnet4_5_20250929, + Model: anthropic.ModelClaudeOpus4_6, }) if err != nil { panic(err.Error()) } fmt.Printf("%+v\n", message.Content) } - -``` - -
-Conversations - -```go -messages := []anthropic.MessageParam{ - anthropic.NewUserMessage(anthropic.NewTextBlock("What is my first name?")), -} - -message, err := client.Messages.New(context.TODO(), anthropic.MessageNewParams{ - Model: anthropic.ModelClaudeSonnet4_5_20250929, - Messages: messages, - MaxTokens: 1024, -}) -if err != nil { - panic(err) -} - -fmt.Printf("%+v\n", message.Content) - -messages = append(messages, message.ToParam()) -messages = append(messages, anthropic.NewUserMessage( - anthropic.NewTextBlock("My full name is John Doe"), -)) - -message, err = client.Messages.New(context.TODO(), anthropic.MessageNewParams{ - Model: anthropic.ModelClaudeSonnet4_5_20250929, - Messages: messages, - MaxTokens: 1024, -}) - -fmt.Printf("%+v\n", message.Content) -``` - -
- -
-System prompts - -```go -message, err := client.Messages.New(context.TODO(), anthropic.MessageNewParams{ - Model: anthropic.ModelClaudeSonnet4_5_20250929, - MaxTokens: 1024, - System: []anthropic.TextBlockParam{ - {Text: "Be very serious at all times."}, - }, - Messages: messages, -}) -``` - -
- -
-Streaming - -```go -content := "What is a quaternion?" - -stream := client.Messages.NewStreaming(context.TODO(), anthropic.MessageNewParams{ - Model: anthropic.ModelClaudeSonnet4_5_20250929, - MaxTokens: 1024, - Messages: []anthropic.MessageParam{ - anthropic.NewUserMessage(anthropic.NewTextBlock(content)), - }, -}) - -message := anthropic.Message{} -for stream.Next() { - event := stream.Current() - err := message.Accumulate(event) - if err != nil { - panic(err) - } - - switch eventVariant := event.AsAny().(type) { - case anthropic.ContentBlockDeltaEvent: - switch deltaVariant := eventVariant.Delta.AsAny().(type) { - case anthropic.TextDelta: - print(deltaVariant.Text) - } - - } -} - -if stream.Err() != nil { - panic(stream.Err()) -} -``` - -
- -
-Tool calling - -```go -package main - -import ( - "context" - "encoding/json" - "fmt" - - "github.com/anthropics/anthropic-sdk-go" - "github.com/invopop/jsonschema" -) - -func main() { - client := anthropic.NewClient() - - content := "Where is San Francisco?" - - println("[user]: " + content) - - messages := []anthropic.MessageParam{ - anthropic.NewUserMessage(anthropic.NewTextBlock(content)), - } - - toolParams := []anthropic.ToolParam{ - { - Name: "get_coordinates", - Description: anthropic.String("Accepts a place as an address, then returns the latitude and longitude coordinates."), - InputSchema: GetCoordinatesInputSchema, - }, - } - tools := make([]anthropic.ToolUnionParam, len(toolParams)) - for i, toolParam := range toolParams { - tools[i] = anthropic.ToolUnionParam{OfTool: &toolParam} - } - - for { - message, err := client.Messages.New(context.TODO(), anthropic.MessageNewParams{ - Model: anthropic.ModelClaudeSonnet4_5_20250929, - MaxTokens: 1024, - Messages: messages, - Tools: tools, - }) - - if err != nil { - panic(err) - } - - print(color("[assistant]: ")) - for _, block := range message.Content { - switch block := block.AsAny().(type) { - case anthropic.TextBlock: - println(block.Text) - println() - case anthropic.ToolUseBlock: - inputJSON, _ := json.Marshal(block.Input) - println(block.Name + ": " + string(inputJSON)) - println() - } - } - - messages = append(messages, message.ToParam()) - toolResults := []anthropic.ContentBlockParamUnion{} - - for _, block := range message.Content { - switch variant := block.AsAny().(type) { - case anthropic.ToolUseBlock: - print(color("[user (" + block.Name + ")]: ")) - - var response any - switch block.Name { - case "get_coordinates": - var input struct { - Location string `json:"location"` - } - - err := json.Unmarshal([]byte(variant.JSON.Input.Raw()), &input) - if err != nil { - panic(err) - } - - response = GetCoordinates(input.Location) - } - - b, err := json.Marshal(response) - if err != nil { - panic(err) - } - - println(string(b)) - - toolResults = append(toolResults, anthropic.NewToolResultBlock(block.ID, string(b), false)) - } - - } - if len(toolResults) == 0 { - break - } - messages = append(messages, anthropic.NewUserMessage(toolResults...)) - } -} - -type GetCoordinatesInput struct { - Location string `json:"location" jsonschema_description:"The location to look up."` -} - -var GetCoordinatesInputSchema = GenerateSchema[GetCoordinatesInput]() - -type GetCoordinateResponse struct { - Long float64 `json:"long"` - Lat float64 `json:"lat"` -} - -func GetCoordinates(location string) GetCoordinateResponse { - return GetCoordinateResponse{ - Long: -122.4194, - Lat: 37.7749, - } -} - -func GenerateSchema[T any]() anthropic.ToolInputSchemaParam { - reflector := jsonschema.Reflector{ - AllowAdditionalProperties: false, - DoNotReference: true, - } - var v T - - schema := reflector.Reflect(v) - - return anthropic.ToolInputSchemaParam{ - Properties: schema.Properties, - } -} - -func color(s string) string { - return fmt.Sprintf("\033[1;%sm%s\033[0m", "33", s) -} -``` - -
- -
-Tool helpers - -The SDK provides helper functions for defining tools and running automatic conversation loops. Here's a basic example: - -```go -package main - -import ( - "context" - "fmt" - - "github.com/anthropics/anthropic-sdk-go" - "github.com/anthropics/anthropic-sdk-go/toolrunner" -) - -// GetWeatherInput defines the tool input with jsonschema tags for automatic schema generation -type GetWeatherInput struct { - City string `json:"city" jsonschema:"required,description=The city name"` -} - -func main() { - client := anthropic.NewClient() - - // Define a tool - the schema is generated automatically from the struct's jsonschema tags - weatherTool, err := toolrunner.NewBetaToolFromJSONSchema( - "get_weather", - "Get weather for a city", - func(ctx context.Context, input GetWeatherInput) (anthropic.BetaToolResultBlockParamContentUnion, error) { - return anthropic.BetaToolResultBlockParamContentUnion{ - OfText: &anthropic.BetaTextBlockParam{ - Text: fmt.Sprintf("The weather in %s is sunny, 72°F", input.City), - }, - }, nil - }, - ) - if err != nil { - panic(err) - } - - // Create a tool runner that automatically handles the conversation loop - runner := client.Beta.Messages.NewToolRunner([]anthropic.BetaTool{weatherTool}, anthropic.BetaToolRunnerParams{ - BetaMessageNewParams: anthropic.BetaMessageNewParams{ - Model: anthropic.ModelClaudeSonnet4_20250514, - MaxTokens: 1024, - Messages: []anthropic.BetaMessageParam{ - anthropic.NewBetaUserMessage(anthropic.NewBetaTextBlock("What's the weather in Paris?")), - }, - }, - MaxIterations: 5, - }) - - // Run until Claude produces a final response - message, err := runner.RunToCompletion(context.Background()) - if err != nil { - panic(err) - } - fmt.Println(message.Content[0].Text) -} -``` - -For more details, see [tools.md](tools.md). - -
- -### Request fields - -The anthropic library uses the [`omitzero`](https://tip.golang.org/doc/go1.24#encodingjsonpkgencodingjson) -semantics from the Go 1.24+ `encoding/json` release for request fields. - -Required primitive fields (`int64`, `string`, etc.) feature the tag \`json:"...,required"\`. These -fields are always serialized, even their zero values. - -Optional primitive types are wrapped in a `param.Opt[T]`. These fields can be set with the provided constructors, `anthropic.String(string)`, `anthropic.Int(int64)`, etc. - -Any `param.Opt[T]`, map, slice, struct or string enum uses the -tag \`json:"...,omitzero"\`. Its zero value is considered omitted. - -The `param.IsOmitted(any)` function can confirm the presence of any `omitzero` field. - -```go -p := anthropic.ExampleParams{ - ID: "id_xxx", // required property - Name: anthropic.String("..."), // optional property - - Point: anthropic.Point{ - X: 0, // required field will serialize as 0 - Y: anthropic.Int(1), // optional field will serialize as 1 - // ... omitted non-required fields will not be serialized - }, - - Origin: anthropic.Origin{}, // the zero value of [Origin] is considered omitted -} -``` - -To send `null` instead of a `param.Opt[T]`, use `param.Null[T]()`. -To send `null` instead of a struct `T`, use `param.NullStruct[T]()`. - -```go -p.Name = param.Null[string]() // 'null' instead of string -p.Point = param.NullStruct[Point]() // 'null' instead of struct - -param.IsNull(p.Name) // true -param.IsNull(p.Point) // true -``` - -Request structs contain a `.SetExtraFields(map[string]any)` method which can send non-conforming -fields in the request body. Extra fields overwrite any struct fields with a matching -key. - -> [!WARNING] -> For security reasons, only use `SetExtraFields` with trusted data. - -To send a custom value instead of a struct, use `param.Override[T](value)`. - -```go -// In cases where the API specifies a given type, -// but you want to send something else, use [SetExtraFields]: -p.SetExtraFields(map[string]any{ - "x": 0.01, // send "x" as a float instead of int -}) - -// Send a number instead of an object -custom := param.Override[anthropic.FooParams](12) -``` - -### Request unions - -Unions are represented as a struct with fields prefixed by "Of" for each of its variants, -only one field can be non-zero. The non-zero field will be serialized. - -Sub-properties of the union can be accessed via methods on the union struct. -These methods return a mutable pointer to the underlying data, if present. - -```go -// Only one field can be non-zero, use param.IsOmitted() to check if a field is set -type AnimalUnionParam struct { - OfCat *Cat `json:",omitzero,inline` - OfDog *Dog `json:",omitzero,inline` -} - -animal := AnimalUnionParam{ - OfCat: &Cat{ - Name: "Whiskers", - Owner: PersonParam{ - Address: AddressParam{Street: "3333 Coyote Hill Rd", Zip: 0}, - }, - }, -} - -// Mutating a field -if address := animal.GetOwner().GetAddress(); address != nil { - address.ZipCode = 94304 -} -``` - -### Response objects - -All fields in response structs are ordinary value types (not pointers or wrappers). -Response structs also include a special `JSON` field containing metadata about -each property. - -```go -type Animal struct { - Name string `json:"name,nullable"` - Owners int `json:"owners"` - Age int `json:"age"` - JSON struct { - Name respjson.Field - Owner respjson.Field - Age respjson.Field - ExtraFields map[string]respjson.Field - } `json:"-"` -} -``` - -To handle optional data, use the `.Valid()` method on the JSON field. -`.Valid()` returns true if a field is not `null`, not present, or couldn't be marshaled. - -If `.Valid()` is false, the corresponding field will simply be its zero value. - -```go -raw := `{"owners": 1, "name": null}` - -var res Animal -json.Unmarshal([]byte(raw), &res) - -// Accessing regular fields - -res.Owners // 1 -res.Name // "" -res.Age // 0 - -// Optional field checks - -res.JSON.Owners.Valid() // true -res.JSON.Name.Valid() // false -res.JSON.Age.Valid() // false - -// Raw JSON values - -res.JSON.Owners.Raw() // "1" -res.JSON.Name.Raw() == "null" // true -res.JSON.Name.Raw() == respjson.Null // true -res.JSON.Age.Raw() == "" // true -res.JSON.Age.Raw() == respjson.Omitted // true -``` - -These `.JSON` structs also include an `ExtraFields` map containing -any properties in the json response that were not specified -in the struct. This can be useful for API features not yet -present in the SDK. - -```go -body := res.JSON.ExtraFields["my_unexpected_field"].Raw() -``` - -### Response Unions - -In responses, unions are represented by a flattened struct containing all possible fields from each of the -object variants. -To convert it to a variant use the `.AsFooVariant()` method or the `.AsAny()` method if present. - -If a response value union contains primitive values, primitive fields will be alongside -the properties but prefixed with `Of` and feature the tag `json:"...,inline"`. - -```go -type AnimalUnion struct { - // From variants [Dog], [Cat] - Owner Person `json:"owner"` - // From variant [Dog] - DogBreed string `json:"dog_breed"` - // From variant [Cat] - CatBreed string `json:"cat_breed"` - // ... - - JSON struct { - Owner respjson.Field - // ... - } `json:"-"` -} - -// If animal variant -if animal.Owner.Address.ZipCode == "" { - panic("missing zip code") -} - -// Switch on the variant -switch variant := animal.AsAny().(type) { -case Dog: -case Cat: -default: - panic("unexpected type") -} -``` - -### RequestOptions - -This library uses the functional options pattern. Functions defined in the -`option` package return a `RequestOption`, which is a closure that mutates a -`RequestConfig`. These options can be supplied to the client or at individual -requests. For example: - -```go -client := anthropic.NewClient( - // Adds a header to every request made by the client - option.WithHeader("X-Some-Header", "custom_header_info"), -) - -client.Messages.New(context.TODO(), ..., - // Override the header - option.WithHeader("X-Some-Header", "some_other_custom_header_info"), - // Add an undocumented field to the request body, using sjson syntax - option.WithJSONSet("some.json.path", map[string]string{"my": "object"}), -) -``` - -The request option `option.WithDebugLog(nil)` may be helpful while debugging. - -See the [full list of request options](https://pkg.go.dev/github.com/anthropics/anthropic-sdk-go/option). - -### Pagination - -This library provides some conveniences for working with paginated list endpoints. - -You can use `.ListAutoPaging()` methods to iterate through items across all pages: - -```go -iter := client.Messages.Batches.ListAutoPaging(context.TODO(), anthropic.MessageBatchListParams{ - Limit: anthropic.Int(20), -}) -// Automatically fetches more pages as needed. -for iter.Next() { - messageBatch := iter.Current() - fmt.Printf("%+v\n", messageBatch) -} -if err := iter.Err(); err != nil { - panic(err.Error()) -} -``` - -Or you can use simple `.List()` methods to fetch a single page and receive a standard response object -with additional helper methods like `.GetNextPage()`, e.g.: - -```go -page, err := client.Messages.Batches.List(context.TODO(), anthropic.MessageBatchListParams{ - Limit: anthropic.Int(20), -}) -for page != nil { - for _, batch := range page.Data { - fmt.Printf("%+v\n", batch) - } - page, err = page.GetNextPage() -} -if err != nil { - panic(err.Error()) -} -``` - -### Errors - -When the API returns a non-success status code, we return an error with type -`*anthropic.Error`. This contains the `StatusCode`, `*http.Request`, and -`*http.Response` values of the request, as well as the JSON of the error body -(much like other response objects in the SDK). The error also includes the `RequestID` -from the response headers, which is useful for troubleshooting with Anthropic support. - -To handle errors, we recommend that you use the `errors.As` pattern: - -```go -_, err := client.Messages.New(context.TODO(), anthropic.MessageNewParams{ - MaxTokens: 1024, - Messages: []anthropic.MessageParam{{ - Content: []anthropic.ContentBlockParamUnion{{ - OfText: &anthropic.TextBlockParam{ - Text: "x", - }, - }}, - Role: anthropic.MessageParamRoleUser, - }}, - Model: anthropic.ModelClaudeSonnet4_5_20250929, -}) -if err != nil { - var apierr *anthropic.Error - if errors.As(err, &apierr) { - println("Request ID:", apierr.RequestID) - println(string(apierr.DumpRequest(true))) // Prints the serialized HTTP request - println(string(apierr.DumpResponse(true))) // Prints the serialized HTTP response - } - panic(err.Error()) // GET "/v1/messages": 400 Bad Request (Request-ID: req_xxx) { ... } -} -``` - -When other errors occur, they are returned unwrapped; for example, -if HTTP transport fails, you might receive `*url.Error` wrapping `*net.OpError`. - -### Timeouts - -Requests do not time out by default; use context to configure a timeout for a request lifecycle. - -Note that if a request is [retried](#retries), the context timeout does not start over. -To set a per-retry timeout, use `option.WithRequestTimeout()`. - -```go -// This sets the timeout for the request, including all the retries. -ctx, cancel := context.WithTimeout(context.Background(), 5*time.Minute) -defer cancel() -client.Messages.New( - ctx, - anthropic.MessageNewParams{ - MaxTokens: 1024, - Messages: []anthropic.MessageParam{{ - Content: []anthropic.ContentBlockParamUnion{{ - OfText: &anthropic.TextBlockParam{ - Text: "What is a quaternion?", - }, - }}, - Role: anthropic.MessageParamRoleUser, - }}, - Model: anthropic.ModelClaudeSonnet4_5_20250929, - }, - // This sets the per-retry timeout - option.WithRequestTimeout(20*time.Second), -) -``` - -### Long Requests - -> [!IMPORTANT] -> We highly encourage you use the streaming Messages API for longer running requests. - -We do not recommend setting a large `MaxTokens` value without using streaming as some networks may drop idle connections after a certain period of time, which -can cause the request to fail or [timeout](#timeouts) without receiving a response from Anthropic. - -This SDK will also return an error if a non-streaming request is expected to be above roughly 10 minutes long. -Calling `.Messages.NewStreaming()` or [setting a custom timeout](#timeouts) disables this error. - -### File uploads - -Request parameters that correspond to file uploads in multipart requests are typed as -`io.Reader`. The contents of the `io.Reader` will by default be sent as a multipart form -part with the file name of "anonymous_file" and content-type of "application/octet-stream", so we -recommend always specifyig a custom content-type with the `anthropic.File(reader io.Reader, filename string, contentType string)` -helper we provide to easily wrap any `io.Reader` with the appropriate file name and content type. - -```go -// A file from the file system -file, err := os.Open("/path/to/file.json") -anthropic.BetaFileUploadParams{ - File: anthropic.File(file, "custom-name.json", "application/json"), - Betas: []anthropic.AnthropicBeta{anthropic.AnthropicBetaFilesAPI2025_04_14}, -} - -// A file from a string -anthropic.BetaFileUploadParams{ - File: anthropic.File(strings.NewReader("my file contents"), "custom-name.json", "application/json"), - Betas: []anthropic.AnthropicBeta{anthropic.AnthropicBetaFilesAPI2025_04_14}, -} -``` - -The file name and content-type can also be customized by implementing `Name() string` or `ContentType() -string` on the run-time type of `io.Reader`. Note that `os.File` implements `Name() string`, so a -file returned by `os.Open` will be sent with the file name on disk. - -### Retries - -Certain errors will be automatically retried 2 times by default, with a short exponential backoff. -We retry by default all connection errors, 408 Request Timeout, 409 Conflict, 429 Rate Limit, -and >=500 Internal errors. - -You can use the `WithMaxRetries` option to configure or disable this: - -```go -// Configure the default for all requests: -client := anthropic.NewClient( - option.WithMaxRetries(0), // default is 2 -) - -// Override per-request: -client.Messages.New( - context.TODO(), - anthropic.MessageNewParams{ - MaxTokens: 1024, - Messages: []anthropic.MessageParam{{ - Content: []anthropic.ContentBlockParamUnion{{ - OfText: &anthropic.TextBlockParam{ - Text: "What is a quaternion?", - }, - }}, - Role: anthropic.MessageParamRoleUser, - }}, - Model: anthropic.ModelClaudeSonnet4_5_20250929, - }, - option.WithMaxRetries(5), -) -``` - -### Accessing raw response data (e.g. response headers) - -You can access the raw HTTP response data by using the `option.WithResponseInto()` request option. This is useful when -you need to examine response headers, status codes, or other details. - -```go -// Create a variable to store the HTTP response -var response *http.Response -message, err := client.Messages.New( - context.TODO(), - anthropic.MessageNewParams{ - MaxTokens: 1024, - Messages: []anthropic.MessageParam{{ - Content: []anthropic.ContentBlockParamUnion{{ - OfText: &anthropic.TextBlockParam{ - Text: "x", - }, - }}, - Role: anthropic.MessageParamRoleUser, - }}, - Model: anthropic.ModelClaudeSonnet4_5_20250929, - }, - option.WithResponseInto(&response), -) -if err != nil { - // handle error -} -fmt.Printf("%+v\n", message) - -fmt.Printf("Status Code: %d\n", response.StatusCode) -fmt.Printf("Headers: %+#v\n", response.Header) -``` - -### Making custom/undocumented requests - -This library is typed for convenient access to the documented API. If you need to access undocumented -endpoints, params, or response properties, the library can still be used. - -#### Undocumented endpoints - -To make requests to undocumented endpoints, you can use `client.Get`, `client.Post`, and other HTTP verbs. -`RequestOptions` on the client, such as retries, will be respected when making these requests. - -```go -var ( - // params can be an io.Reader, a []byte, an encoding/json serializable object, - // or a "…Params" struct defined in this library. - params map[string]any - - // result can be an []byte, *http.Response, a encoding/json deserializable object, - // or a model defined in this library. - result *http.Response -) -err := client.Post(context.Background(), "/unspecified", params, &result) -if err != nil { - … -} -``` - -#### Undocumented request params - -To make requests using undocumented parameters, you may use either the `option.WithQuerySet()` -or the `option.WithJSONSet()` methods. - -```go -params := FooNewParams{ - ID: "id_xxxx", - Data: FooNewParamsData{ - FirstName: anthropic.String("John"), - }, -} -client.Foo.New(context.Background(), params, option.WithJSONSet("data.last_name", "Doe")) -``` - -#### Undocumented response properties - -To access undocumented response properties, you may either access the raw JSON of the response as a string -with `result.JSON.RawJSON()`, or get the raw JSON of a particular field on the result with -`result.JSON.Foo.Raw()`. - -Any fields that are not present on the response struct will be saved and can be accessed by `result.JSON.ExtraFields()` which returns the extra fields as a `map[string]Field`. - -### Middleware - -We provide `option.WithMiddleware` which applies the given -middleware to requests. - -```go -func Logger(req *http.Request, next option.MiddlewareNext) (res *http.Response, err error) { - // Before the request - start := time.Now() - LogReq(req) - - // Forward the request to the next handler - res, err = next(req) - - // Handle stuff after the request - end := time.Now() - LogRes(res, err, start - end) - - return res, err -} - -client := anthropic.NewClient( - option.WithMiddleware(Logger), -) ``` -When multiple middlewares are provided as variadic arguments, the middlewares -are applied left to right. If `option.WithMiddleware` is given -multiple times, for example first in the client then the method, the -middleware in the client will run first and the middleware given in the method -will run next. - -You may also replace the default `http.Client` with -`option.WithHTTPClient(client)`. Only one http client is -accepted (this overwrites any previous client) and receives requests after any -middleware has been applied. - -## Amazon Bedrock - -To use this library with [Amazon Bedrock](https://aws.amazon.com/bedrock/claude/), -use the bedrock request option `bedrock.WithLoadDefaultConfig(…)` which reads the -[default config](https://docs.aws.amazon.com/cli/latest/userguide/cli-chap-configure.html). - -Importing the `bedrock` library also globally registers a decoder for `application/vnd.amazon.eventstream` for -streaming. - -```go -package main - -import ( - "github.com/anthropics/anthropic-sdk-go" - "github.com/anthropics/anthropic-sdk-go/bedrock" -) - -func main() { - client := anthropic.NewClient( - bedrock.WithLoadDefaultConfig(context.Background()), - ) -} -``` - -If you already have an `aws.Config`, you can also use it directly with `bedrock.WithConfig(cfg)`. - -### Bearer Token Authentication - -You can also authenticate with Bedrock using bearer tokens instead of AWS credentials. This is useful in corporate environments where teams need access to Bedrock without managing AWS credentials, IAM roles, or account-level permissions. - -The simplest approach is to set the `AWS_BEARER_TOKEN_BEDROCK` environment variable: - -```go -package main - -import ( - "context" - - "github.com/anthropics/anthropic-sdk-go" - "github.com/anthropics/anthropic-sdk-go/bedrock" -) - -func main() { - // Automatically uses AWS_BEARER_TOKEN_BEDROCK from the environment. - // Region defaults to us-east-1 or uses AWS_REGION if set. - client := anthropic.NewClient( - bedrock.WithLoadDefaultConfig(context.Background()), - ) -} -``` - -To provide a token programmatically, use `bedrock.WithConfig` with a `BearerAuthTokenProvider`: - -```go -package main - -import ( - "context" - - "github.com/anthropics/anthropic-sdk-go" - "github.com/anthropics/anthropic-sdk-go/bedrock" - "github.com/aws/aws-sdk-go-v2/aws" -) - -func main() { - cfg := aws.Config{ - Region: "us-west-2", - BearerAuthTokenProvider: bedrock.NewStaticBearerTokenProvider("your-bearer-token"), - } - client := anthropic.NewClient( - bedrock.WithConfig(cfg), - ) -} -``` - -Read more about Anthropic and Amazon Bedrock [here](https://docs.anthropic.com/en/api/claude-on-amazon-bedrock) and about Bedrock API keys [here](https://docs.aws.amazon.com/bedrock/latest/userguide/api-keys-use.html). - -## Google Vertex AI - -To use this library with [Google Vertex AI](https://cloud.google.com/vertex-ai/generative-ai/docs/partner-models/use-claude), -use the request option `vertex.WithGoogleAuth(…)` which reads the -[Application Default Credentials](https://cloud.google.com/docs/authentication/application-default-credentials). - -```go -package main - -import ( - "context" - - "github.com/anthropics/anthropic-sdk-go" - "github.com/anthropics/anthropic-sdk-go/vertex" -) - -func main() { - client := anthropic.NewClient( - vertex.WithGoogleAuth(context.Background(), "us-central1", "id-xxx"), - ) -} -``` - -If you already have `*google.Credentials`, you can also use it directly with -`vertex.WithCredentials(ctx, region, projectId, creds)`. - -Read more about Anthropic and Google Vertex [here](https://docs.anthropic.com/en/api/claude-on-vertex-ai). - -## Semantic versioning - -This package generally follows [SemVer](https://semver.org/spec/v2.0.0.html) conventions, though certain backwards-incompatible changes may be released as minor versions: +## Requirements -1. Changes to library internals which are technically public but not intended or documented for external use. _(Please open a GitHub issue to let us know if you are relying on such internals.)_ -2. Changes that we do not expect to impact the vast majority of users in practice. +Go 1.22+ -We take backwards-compatibility seriously and work hard to ensure you can rely on a smooth upgrade experience. +## Contributing -We are keen for your feedback; please open an [issue](https://www.github.com/anthropics/anthropic-sdk-go/issues) with questions, bugs, or suggestions. +See [CONTRIBUTING.md](./CONTRIBUTING.md). -## Contributing +## License -See [the contributing documentation](./CONTRIBUTING.md). +This project is licensed under the MIT License. See the [LICENSE](LICENSE) file for details. diff --git a/api.md b/api.md index 4ee4ec97..2137f50f 100644 --- a/api.md +++ b/api.md @@ -99,6 +99,7 @@ Params Types: - anthropic.WebFetchBlockParam - anthropic.WebFetchTool20250910Param - anthropic.WebFetchTool20260209Param +- anthropic.WebFetchTool20260309Param - anthropic.WebFetchToolResultBlockParam - anthropic.WebFetchToolResultErrorBlockParam - anthropic.WebFetchToolResultErrorCode @@ -366,6 +367,7 @@ Params Types: - anthropic.BetaWebFetchBlockParam - anthropic.BetaWebFetchTool20250910Param - anthropic.BetaWebFetchTool20260209Param +- anthropic.BetaWebFetchTool20260309Param - anthropic.BetaWebFetchToolResultBlockParam - anthropic.BetaWebFetchToolResultErrorBlockParam - anthropic.BetaWebFetchToolResultErrorCode diff --git a/beta.go b/beta.go index 3bd99c7d..18c62a2b 100644 --- a/beta.go +++ b/beta.go @@ -64,8 +64,8 @@ const ( ) type BetaAPIError struct { - Message string `json:"message,required"` - Type constant.APIError `json:"type,required"` + Message string `json:"message" api:"required"` + Type constant.APIError `json:"type" api:"required"` // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. JSON struct { Message respjson.Field @@ -82,8 +82,8 @@ func (r *BetaAPIError) UnmarshalJSON(data []byte) error { } type BetaAuthenticationError struct { - Message string `json:"message,required"` - Type constant.AuthenticationError `json:"type,required"` + Message string `json:"message" api:"required"` + Type constant.AuthenticationError `json:"type" api:"required"` // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. JSON struct { Message respjson.Field @@ -100,8 +100,8 @@ func (r *BetaAuthenticationError) UnmarshalJSON(data []byte) error { } type BetaBillingError struct { - Message string `json:"message,required"` - Type constant.BillingError `json:"type,required"` + Message string `json:"message" api:"required"` + Type constant.BillingError `json:"type" api:"required"` // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. JSON struct { Message respjson.Field @@ -246,9 +246,9 @@ func (r *BetaErrorUnion) UnmarshalJSON(data []byte) error { } type BetaErrorResponse struct { - Error BetaErrorUnion `json:"error,required"` - RequestID string `json:"request_id,required"` - Type constant.Error `json:"type,required"` + Error BetaErrorUnion `json:"error" api:"required"` + RequestID string `json:"request_id" api:"required"` + Type constant.Error `json:"type" api:"required"` // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. JSON struct { Error respjson.Field @@ -266,8 +266,8 @@ func (r *BetaErrorResponse) UnmarshalJSON(data []byte) error { } type BetaGatewayTimeoutError struct { - Message string `json:"message,required"` - Type constant.TimeoutError `json:"type,required"` + Message string `json:"message" api:"required"` + Type constant.TimeoutError `json:"type" api:"required"` // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. JSON struct { Message respjson.Field @@ -284,8 +284,8 @@ func (r *BetaGatewayTimeoutError) UnmarshalJSON(data []byte) error { } type BetaInvalidRequestError struct { - Message string `json:"message,required"` - Type constant.InvalidRequestError `json:"type,required"` + Message string `json:"message" api:"required"` + Type constant.InvalidRequestError `json:"type" api:"required"` // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. JSON struct { Message respjson.Field @@ -302,8 +302,8 @@ func (r *BetaInvalidRequestError) UnmarshalJSON(data []byte) error { } type BetaNotFoundError struct { - Message string `json:"message,required"` - Type constant.NotFoundError `json:"type,required"` + Message string `json:"message" api:"required"` + Type constant.NotFoundError `json:"type" api:"required"` // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. JSON struct { Message respjson.Field @@ -320,8 +320,8 @@ func (r *BetaNotFoundError) UnmarshalJSON(data []byte) error { } type BetaOverloadedError struct { - Message string `json:"message,required"` - Type constant.OverloadedError `json:"type,required"` + Message string `json:"message" api:"required"` + Type constant.OverloadedError `json:"type" api:"required"` // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. JSON struct { Message respjson.Field @@ -338,8 +338,8 @@ func (r *BetaOverloadedError) UnmarshalJSON(data []byte) error { } type BetaPermissionError struct { - Message string `json:"message,required"` - Type constant.PermissionError `json:"type,required"` + Message string `json:"message" api:"required"` + Type constant.PermissionError `json:"type" api:"required"` // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. JSON struct { Message respjson.Field @@ -356,8 +356,8 @@ func (r *BetaPermissionError) UnmarshalJSON(data []byte) error { } type BetaRateLimitError struct { - Message string `json:"message,required"` - Type constant.RateLimitError `json:"type,required"` + Message string `json:"message" api:"required"` + Type constant.RateLimitError `json:"type" api:"required"` // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. JSON struct { Message respjson.Field diff --git a/betafile.go b/betafile.go index 8d09ee06..687dbf80 100644 --- a/betafile.go +++ b/betafile.go @@ -79,11 +79,11 @@ func (r *BetaFileService) Delete(ctx context.Context, fileID string, body BetaFi opts = append([]option.RequestOption{option.WithHeader("anthropic-beta", "files-api-2025-04-14")}, opts...) if fileID == "" { err = errors.New("missing required file_id parameter") - return + return nil, err } path := fmt.Sprintf("v1/files/%s?beta=true", fileID) err = requestconfig.ExecuteNewRequest(ctx, http.MethodDelete, path, nil, &res, opts...) - return + return res, err } // Download File @@ -95,11 +95,11 @@ func (r *BetaFileService) Download(ctx context.Context, fileID string, query Bet opts = append([]option.RequestOption{option.WithHeader("anthropic-beta", "files-api-2025-04-14"), option.WithHeader("Accept", "application/binary")}, opts...) if fileID == "" { err = errors.New("missing required file_id parameter") - return + return nil, err } path := fmt.Sprintf("v1/files/%s/content?beta=true", fileID) err = requestconfig.ExecuteNewRequest(ctx, http.MethodGet, path, nil, &res, opts...) - return + return res, err } // Get File Metadata @@ -111,11 +111,11 @@ func (r *BetaFileService) GetMetadata(ctx context.Context, fileID string, query opts = append([]option.RequestOption{option.WithHeader("anthropic-beta", "files-api-2025-04-14")}, opts...) if fileID == "" { err = errors.New("missing required file_id parameter") - return + return nil, err } path := fmt.Sprintf("v1/files/%s?beta=true", fileID) err = requestconfig.ExecuteNewRequest(ctx, http.MethodGet, path, nil, &res, opts...) - return + return res, err } // Upload File @@ -127,12 +127,12 @@ func (r *BetaFileService) Upload(ctx context.Context, params BetaFileUploadParam opts = append([]option.RequestOption{option.WithHeader("anthropic-beta", "files-api-2025-04-14")}, opts...) path := "v1/files?beta=true" err = requestconfig.ExecuteNewRequest(ctx, http.MethodPost, path, params, &res, opts...) - return + return res, err } type DeletedFile struct { // ID of the deleted file. - ID string `json:"id,required"` + ID string `json:"id" api:"required"` // Deleted object type. // // For file deletion, this is always `"file_deleted"`. @@ -167,19 +167,19 @@ type FileMetadata struct { // Unique object identifier. // // The format and length of IDs may change over time. - ID string `json:"id,required"` + ID string `json:"id" api:"required"` // RFC 3339 datetime string representing when the file was created. - CreatedAt time.Time `json:"created_at,required" format:"date-time"` + CreatedAt time.Time `json:"created_at" api:"required" format:"date-time"` // Original filename of the uploaded file. - Filename string `json:"filename,required"` + Filename string `json:"filename" api:"required"` // MIME type of the file. - MimeType string `json:"mime_type,required"` + MimeType string `json:"mime_type" api:"required"` // Size of the file in bytes. - SizeBytes int64 `json:"size_bytes,required"` + SizeBytes int64 `json:"size_bytes" api:"required"` // Object type. // // For files, this is always `"file"`. - Type constant.File `json:"type,required"` + Type constant.File `json:"type" api:"required"` // Whether the file can be downloaded. Downloadable bool `json:"downloadable"` // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. @@ -246,7 +246,7 @@ type BetaFileGetMetadataParams struct { type BetaFileUploadParams struct { // The file to upload - File io.Reader `json:"file,omitzero,required" format:"binary"` + File io.Reader `json:"file,omitzero" api:"required" format:"binary"` // Optional header to specify the beta version(s) you want to use. Betas []AnthropicBeta `header:"anthropic-beta,omitzero" json:"-"` paramObj diff --git a/betafile_test.go b/betafile_test.go index 872c87ce..42cd75c2 100644 --- a/betafile_test.go +++ b/betafile_test.go @@ -153,7 +153,7 @@ func TestBetaFileUploadWithOptionalParams(t *testing.T) { option.WithAPIKey("my-anthropic-api-key"), ) _, err := client.Beta.Files.Upload(context.TODO(), anthropic.BetaFileUploadParams{ - File: io.Reader(bytes.NewBuffer([]byte("some file contents"))), + File: io.Reader(bytes.NewBuffer([]byte("Example data"))), Betas: []anthropic.AnthropicBeta{anthropic.AnthropicBetaMessageBatches2024_09_24}, }) if err != nil { diff --git a/betamessage.go b/betamessage.go index 47bd6ee9..dc167ebb 100644 --- a/betamessage.go +++ b/betamessage.go @@ -67,7 +67,7 @@ func (r *BetaMessageService) New(ctx context.Context, params BetaMessageNewParam path := "v1/messages?beta=true" err = requestconfig.ExecuteNewRequest(ctx, http.MethodPost, path, params, &res, opts...) - return + return res, err } // Send a structured list of input messages with text and/or image content, and the @@ -109,7 +109,7 @@ func (r *BetaMessageService) CountTokens(ctx context.Context, params BetaMessage opts = slices.Concat(r.Options, opts) path := "v1/messages/count_tokens?beta=true" err = requestconfig.ExecuteNewRequest(ctx, http.MethodPost, path, params, &res, opts...) - return + return res, err } func NewBetaAllThinkingTurnsParam() BetaAllThinkingTurnsParam { @@ -121,7 +121,7 @@ func NewBetaAllThinkingTurnsParam() BetaAllThinkingTurnsParam { // This struct has a constant value, construct it with // [NewBetaAllThinkingTurnsParam]. type BetaAllThinkingTurnsParam struct { - Type constant.All `json:"type,required"` + Type constant.All `json:"type" api:"required"` paramObj } @@ -135,11 +135,11 @@ func (r *BetaAllThinkingTurnsParam) UnmarshalJSON(data []byte) error { // The properties Data, MediaType, Type are required. type BetaBase64ImageSourceParam struct { - Data string `json:"data,required" format:"byte"` + Data string `json:"data" api:"required" format:"byte"` // Any of "image/jpeg", "image/png", "image/gif", "image/webp". - MediaType BetaBase64ImageSourceMediaType `json:"media_type,omitzero,required"` + MediaType BetaBase64ImageSourceMediaType `json:"media_type,omitzero" api:"required"` // This field can be elided, and will marshal its zero value as "base64". - Type constant.Base64 `json:"type,required"` + Type constant.Base64 `json:"type" api:"required"` paramObj } @@ -160,256 +160,10 @@ const ( BetaBase64ImageSourceMediaTypeImageWebP BetaBase64ImageSourceMediaType = "image/webp" ) -// The properties Source, Type are required. -type BetaBase64PDFBlockParam struct { - Source BetaBase64PDFBlockSourceUnionParam `json:"source,omitzero,required"` - Context param.Opt[string] `json:"context,omitzero"` - Title param.Opt[string] `json:"title,omitzero"` - // Create a cache control breakpoint at this content block. - CacheControl BetaCacheControlEphemeralParam `json:"cache_control,omitzero"` - Citations BetaCitationsConfigParam `json:"citations,omitzero"` - // This field can be elided, and will marshal its zero value as "document". - Type constant.Document `json:"type,required"` - paramObj -} - -func (r BetaBase64PDFBlockParam) MarshalJSON() (data []byte, err error) { - type shadow BetaBase64PDFBlockParam - return param.MarshalObject(r, (*shadow)(&r)) -} -func (r *BetaBase64PDFBlockParam) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} - -// Only one field can be non-zero. -// -// Use [param.IsOmitted] to confirm if a field is set. -type BetaBase64PDFBlockSourceUnionParam struct { - OfBase64 *BetaBase64PDFSourceParam `json:",omitzero,inline"` - OfText *BetaPlainTextSourceParam `json:",omitzero,inline"` - OfContent *BetaContentBlockSourceParam `json:",omitzero,inline"` - OfURL *BetaURLPDFSourceParam `json:",omitzero,inline"` - OfFile *BetaFileDocumentSourceParam `json:",omitzero,inline"` - paramUnion -} - -func (u BetaBase64PDFBlockSourceUnionParam) MarshalJSON() ([]byte, error) { - return param.MarshalUnion(u, u.OfBase64, - u.OfText, - u.OfContent, - u.OfURL, - u.OfFile) -} -func (u *BetaBase64PDFBlockSourceUnionParam) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, u) -} - -func (u *BetaBase64PDFBlockSourceUnionParam) asAny() any { - if !param.IsOmitted(u.OfBase64) { - return u.OfBase64 - } else if !param.IsOmitted(u.OfText) { - return u.OfText - } else if !param.IsOmitted(u.OfContent) { - return u.OfContent - } else if !param.IsOmitted(u.OfURL) { - return u.OfURL - } else if !param.IsOmitted(u.OfFile) { - return u.OfFile - } - return nil -} - -// Returns a pointer to the underlying variant's property, if present. -func (u BetaBase64PDFBlockSourceUnionParam) GetContent() *BetaContentBlockSourceContentUnionParam { - if vt := u.OfContent; vt != nil { - return &vt.Content - } - return nil -} - -// Returns a pointer to the underlying variant's property, if present. -func (u BetaBase64PDFBlockSourceUnionParam) GetURL() *string { - if vt := u.OfURL; vt != nil { - return &vt.URL - } - return nil -} - -// Returns a pointer to the underlying variant's property, if present. -func (u BetaBase64PDFBlockSourceUnionParam) GetFileID() *string { - if vt := u.OfFile; vt != nil { - return &vt.FileID - } - return nil -} - -// Returns a pointer to the underlying variant's property, if present. -func (u BetaBase64PDFBlockSourceUnionParam) GetData() *string { - if vt := u.OfBase64; vt != nil { - return (*string)(&vt.Data) - } else if vt := u.OfText; vt != nil { - return (*string)(&vt.Data) - } - return nil -} - -// Returns a pointer to the underlying variant's property, if present. -func (u BetaBase64PDFBlockSourceUnionParam) GetMediaType() *string { - if vt := u.OfBase64; vt != nil { - return (*string)(&vt.MediaType) - } else if vt := u.OfText; vt != nil { - return (*string)(&vt.MediaType) - } - return nil -} - -// Returns a pointer to the underlying variant's property, if present. -func (u BetaBase64PDFBlockSourceUnionParam) GetType() *string { - if vt := u.OfBase64; vt != nil { - return (*string)(&vt.Type) - } else if vt := u.OfText; vt != nil { - return (*string)(&vt.Type) - } else if vt := u.OfContent; vt != nil { - return (*string)(&vt.Type) - } else if vt := u.OfURL; vt != nil { - return (*string)(&vt.Type) - } else if vt := u.OfFile; vt != nil { - return (*string)(&vt.Type) - } - return nil -} - -func init() { - apijson.RegisterUnion[BetaBase64PDFBlockSourceUnionParam]( - "type", - apijson.Discriminator[BetaBase64PDFSourceParam]("base64"), - apijson.Discriminator[BetaPlainTextSourceParam]("text"), - apijson.Discriminator[BetaContentBlockSourceParam]("content"), - apijson.Discriminator[BetaURLPDFSourceParam]("url"), - apijson.Discriminator[BetaFileDocumentSourceParam]("file"), - ) -} - -func init() { - apijson.RegisterUnion[BetaImageBlockParamSourceUnion]( - "type", - apijson.Discriminator[BetaBase64ImageSourceParam]("base64"), - apijson.Discriminator[BetaURLImageSourceParam]("url"), - apijson.Discriminator[BetaFileImageSourceParam]("file"), - ) -} - -func init() { - apijson.RegisterUnion[BetaRequestDocumentBlockSourceUnionParam]( - "type", - apijson.Discriminator[BetaBase64PDFSourceParam]("base64"), - apijson.Discriminator[BetaPlainTextSourceParam]("text"), - apijson.Discriminator[BetaContentBlockSourceParam]("content"), - apijson.Discriminator[BetaURLPDFSourceParam]("url"), - apijson.Discriminator[BetaFileDocumentSourceParam]("file"), - ) -} - -func init() { - apijson.RegisterUnion[BetaTextCitationParamUnion]( - "type", - apijson.Discriminator[BetaCitationCharLocationParam]("char_location"), - apijson.Discriminator[BetaCitationPageLocationParam]("page_location"), - apijson.Discriminator[BetaCitationContentBlockLocationParam]("content_block_location"), - apijson.Discriminator[BetaCitationWebSearchResultLocationParam]("web_search_result_location"), - apijson.Discriminator[BetaCitationSearchResultLocationParam]("search_result_location"), - ) -} - -func init() { - apijson.RegisterUnion[BetaThinkingConfigParamUnion]( - "type", - apijson.Discriminator[BetaThinkingConfigEnabledParam]("enabled"), - apijson.Discriminator[BetaThinkingConfigDisabledParam]("disabled"), - ) -} - -func init() { - apijson.RegisterUnion[BetaToolChoiceUnionParam]( - "type", - apijson.Discriminator[BetaToolChoiceAutoParam]("auto"), - apijson.Discriminator[BetaToolChoiceAnyParam]("any"), - apijson.Discriminator[BetaToolChoiceToolParam]("tool"), - apijson.Discriminator[BetaToolChoiceNoneParam]("none"), - ) -} - -func init() { - apijson.RegisterUnion[BetaClearToolUses20250919EditTriggerUnionParam]( - "type", - apijson.Discriminator[BetaInputTokensTriggerParam]("input_tokens"), - apijson.Discriminator[BetaToolUsesTriggerParam]("tool_uses"), - ) -} - -func init() { - apijson.RegisterUnion[BetaContentBlockParamUnion]( - "type", - apijson.Discriminator[BetaTextBlockParam]("text"), - apijson.Discriminator[BetaImageBlockParam]("image"), - apijson.Discriminator[BetaRequestDocumentBlockParam]("document"), - apijson.Discriminator[BetaSearchResultBlockParam]("search_result"), - apijson.Discriminator[BetaThinkingBlockParam]("thinking"), - apijson.Discriminator[BetaRedactedThinkingBlockParam]("redacted_thinking"), - apijson.Discriminator[BetaToolUseBlockParam]("tool_use"), - apijson.Discriminator[BetaToolResultBlockParam]("tool_result"), - apijson.Discriminator[BetaServerToolUseBlockParam]("server_tool_use"), - apijson.Discriminator[BetaWebSearchToolResultBlockParam]("web_search_tool_result"), - apijson.Discriminator[BetaWebFetchToolResultBlockParam]("web_fetch_tool_result"), - apijson.Discriminator[BetaCodeExecutionToolResultBlockParam]("code_execution_tool_result"), - apijson.Discriminator[BetaBashCodeExecutionToolResultBlockParam]("bash_code_execution_tool_result"), - apijson.Discriminator[BetaTextEditorCodeExecutionToolResultBlockParam]("text_editor_code_execution_tool_result"), - apijson.Discriminator[BetaToolSearchToolResultBlockParam]("tool_search_tool_result"), - apijson.Discriminator[BetaMCPToolUseBlockParam]("mcp_tool_use"), - apijson.Discriminator[BetaRequestMCPToolResultBlockParam]("mcp_tool_result"), - apijson.Discriminator[BetaContainerUploadBlockParam]("container_upload"), - ) -} - -func init() { - apijson.RegisterUnion[BetaContextManagementConfigEditUnionParam]( - "type", - apijson.Discriminator[BetaClearToolUses20250919EditParam]("clear_tool_uses_20250919"), - apijson.Discriminator[BetaClearThinking20251015EditParam]("clear_thinking_20251015"), - ) -} - -func init() { - apijson.RegisterUnion[BetaServerToolUseBlockParamCallerUnion]( - "type", - apijson.Discriminator[BetaDirectCallerParam]("direct"), - apijson.Discriminator[BetaServerToolCallerParam]("code_execution_20250825"), - ) -} - -func init() { - apijson.RegisterUnion[BetaToolResultBlockParamContentUnion]( - "type", - apijson.Discriminator[BetaTextBlockParam]("text"), - apijson.Discriminator[BetaImageBlockParam]("image"), - apijson.Discriminator[BetaSearchResultBlockParam]("search_result"), - apijson.Discriminator[BetaRequestDocumentBlockParam]("document"), - apijson.Discriminator[BetaToolReferenceBlockParam]("tool_reference"), - ) -} - -func init() { - apijson.RegisterUnion[BetaToolUseBlockParamCallerUnion]( - "type", - apijson.Discriminator[BetaDirectCallerParam]("direct"), - apijson.Discriminator[BetaServerToolCallerParam]("code_execution_20250825"), - ) -} - type BetaBase64PDFSource struct { - Data string `json:"data,required" format:"byte"` - MediaType constant.ApplicationPDF `json:"media_type,required"` - Type constant.Base64 `json:"type,required"` + Data string `json:"data" api:"required" format:"byte"` + MediaType constant.ApplicationPDF `json:"media_type" api:"required"` + Type constant.Base64 `json:"type" api:"required"` // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. JSON struct { Data respjson.Field @@ -437,11 +191,11 @@ func (r BetaBase64PDFSource) ToParam() BetaBase64PDFSourceParam { // The properties Data, MediaType, Type are required. type BetaBase64PDFSourceParam struct { - Data string `json:"data,required" format:"byte"` + Data string `json:"data" api:"required" format:"byte"` // This field can be elided, and will marshal its zero value as "application/pdf". - MediaType constant.ApplicationPDF `json:"media_type,required"` + MediaType constant.ApplicationPDF `json:"media_type" api:"required"` // This field can be elided, and will marshal its zero value as "base64". - Type constant.Base64 `json:"type,required"` + Type constant.Base64 `json:"type" api:"required"` paramObj } @@ -454,8 +208,8 @@ func (r *BetaBase64PDFSourceParam) UnmarshalJSON(data []byte) error { } type BetaBashCodeExecutionOutputBlock struct { - FileID string `json:"file_id,required"` - Type constant.BashCodeExecutionOutput `json:"type,required"` + FileID string `json:"file_id" api:"required"` + Type constant.BashCodeExecutionOutput `json:"type" api:"required"` // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. JSON struct { FileID respjson.Field @@ -473,10 +227,10 @@ func (r *BetaBashCodeExecutionOutputBlock) UnmarshalJSON(data []byte) error { // The properties FileID, Type are required. type BetaBashCodeExecutionOutputBlockParam struct { - FileID string `json:"file_id,required"` + FileID string `json:"file_id" api:"required"` // This field can be elided, and will marshal its zero value as // "bash_code_execution_output". - Type constant.BashCodeExecutionOutput `json:"type,required"` + Type constant.BashCodeExecutionOutput `json:"type" api:"required"` paramObj } @@ -489,11 +243,11 @@ func (r *BetaBashCodeExecutionOutputBlockParam) UnmarshalJSON(data []byte) error } type BetaBashCodeExecutionResultBlock struct { - Content []BetaBashCodeExecutionOutputBlock `json:"content,required"` - ReturnCode int64 `json:"return_code,required"` - Stderr string `json:"stderr,required"` - Stdout string `json:"stdout,required"` - Type constant.BashCodeExecutionResult `json:"type,required"` + Content []BetaBashCodeExecutionOutputBlock `json:"content" api:"required"` + ReturnCode int64 `json:"return_code" api:"required"` + Stderr string `json:"stderr" api:"required"` + Stdout string `json:"stdout" api:"required"` + Type constant.BashCodeExecutionResult `json:"type" api:"required"` // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. JSON struct { Content respjson.Field @@ -514,13 +268,13 @@ func (r *BetaBashCodeExecutionResultBlock) UnmarshalJSON(data []byte) error { // The properties Content, ReturnCode, Stderr, Stdout, Type are required. type BetaBashCodeExecutionResultBlockParam struct { - Content []BetaBashCodeExecutionOutputBlockParam `json:"content,omitzero,required"` - ReturnCode int64 `json:"return_code,required"` - Stderr string `json:"stderr,required"` - Stdout string `json:"stdout,required"` + Content []BetaBashCodeExecutionOutputBlockParam `json:"content,omitzero" api:"required"` + ReturnCode int64 `json:"return_code" api:"required"` + Stderr string `json:"stderr" api:"required"` + Stdout string `json:"stdout" api:"required"` // This field can be elided, and will marshal its zero value as // "bash_code_execution_result". - Type constant.BashCodeExecutionResult `json:"type,required"` + Type constant.BashCodeExecutionResult `json:"type" api:"required"` paramObj } @@ -533,9 +287,9 @@ func (r *BetaBashCodeExecutionResultBlockParam) UnmarshalJSON(data []byte) error } type BetaBashCodeExecutionToolResultBlock struct { - Content BetaBashCodeExecutionToolResultBlockContentUnion `json:"content,required"` - ToolUseID string `json:"tool_use_id,required"` - Type constant.BashCodeExecutionToolResult `json:"type,required"` + Content BetaBashCodeExecutionToolResultBlockContentUnion `json:"content" api:"required"` + ToolUseID string `json:"tool_use_id" api:"required"` + Type constant.BashCodeExecutionToolResult `json:"type" api:"required"` // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. JSON struct { Content respjson.Field @@ -599,13 +353,13 @@ func (r *BetaBashCodeExecutionToolResultBlockContentUnion) UnmarshalJSON(data [] // The properties Content, ToolUseID, Type are required. type BetaBashCodeExecutionToolResultBlockParam struct { - Content BetaBashCodeExecutionToolResultBlockParamContentUnion `json:"content,omitzero,required"` - ToolUseID string `json:"tool_use_id,required"` + Content BetaBashCodeExecutionToolResultBlockParamContentUnion `json:"content,omitzero" api:"required"` + ToolUseID string `json:"tool_use_id" api:"required"` // Create a cache control breakpoint at this content block. CacheControl BetaCacheControlEphemeralParam `json:"cache_control,omitzero"` // This field can be elided, and will marshal its zero value as // "bash_code_execution_tool_result". - Type constant.BashCodeExecutionToolResult `json:"type,required"` + Type constant.BashCodeExecutionToolResult `json:"type" api:"required"` paramObj } @@ -695,8 +449,8 @@ func (u BetaBashCodeExecutionToolResultBlockParamContentUnion) GetType() *string type BetaBashCodeExecutionToolResultError struct { // Any of "invalid_tool_input", "unavailable", "too_many_requests", // "execution_time_exceeded", "output_file_too_large". - ErrorCode BetaBashCodeExecutionToolResultErrorErrorCode `json:"error_code,required"` - Type constant.BashCodeExecutionToolResultError `json:"type,required"` + ErrorCode BetaBashCodeExecutionToolResultErrorErrorCode `json:"error_code" api:"required"` + Type constant.BashCodeExecutionToolResultError `json:"type" api:"required"` // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. JSON struct { ErrorCode respjson.Field @@ -726,10 +480,10 @@ const ( type BetaBashCodeExecutionToolResultErrorParam struct { // Any of "invalid_tool_input", "unavailable", "too_many_requests", // "execution_time_exceeded", "output_file_too_large". - ErrorCode BetaBashCodeExecutionToolResultErrorParamErrorCode `json:"error_code,omitzero,required"` + ErrorCode BetaBashCodeExecutionToolResultErrorParamErrorCode `json:"error_code,omitzero" api:"required"` // This field can be elided, and will marshal its zero value as // "bash_code_execution_tool_result_error". - Type constant.BashCodeExecutionToolResultError `json:"type,required"` + Type constant.BashCodeExecutionToolResultError `json:"type" api:"required"` paramObj } @@ -771,7 +525,7 @@ type BetaCacheControlEphemeralParam struct { // // Any of "5m", "1h". TTL BetaCacheControlEphemeralTTL `json:"ttl,omitzero"` - Type constant.Ephemeral `json:"type,required"` + Type constant.Ephemeral `json:"type" api:"required"` paramObj } @@ -800,9 +554,9 @@ const ( type BetaCacheCreation struct { // The number of input tokens used to create the 1 hour cache entry. - Ephemeral1hInputTokens int64 `json:"ephemeral_1h_input_tokens,required"` + Ephemeral1hInputTokens int64 `json:"ephemeral_1h_input_tokens" api:"required"` // The number of input tokens used to create the 5 minute cache entry. - Ephemeral5mInputTokens int64 `json:"ephemeral_5m_input_tokens,required"` + Ephemeral5mInputTokens int64 `json:"ephemeral_5m_input_tokens" api:"required"` // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. JSON struct { Ephemeral1hInputTokens respjson.Field @@ -819,13 +573,13 @@ func (r *BetaCacheCreation) UnmarshalJSON(data []byte) error { } type BetaCitationCharLocation struct { - CitedText string `json:"cited_text,required"` - DocumentIndex int64 `json:"document_index,required"` - DocumentTitle string `json:"document_title,required"` - EndCharIndex int64 `json:"end_char_index,required"` - FileID string `json:"file_id,required"` - StartCharIndex int64 `json:"start_char_index,required"` - Type constant.CharLocation `json:"type,required"` + CitedText string `json:"cited_text" api:"required"` + DocumentIndex int64 `json:"document_index" api:"required"` + DocumentTitle string `json:"document_title" api:"required"` + EndCharIndex int64 `json:"end_char_index" api:"required"` + FileID string `json:"file_id" api:"required"` + StartCharIndex int64 `json:"start_char_index" api:"required"` + Type constant.CharLocation `json:"type" api:"required"` // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. JSON struct { CitedText respjson.Field @@ -849,13 +603,13 @@ func (r *BetaCitationCharLocation) UnmarshalJSON(data []byte) error { // The properties CitedText, DocumentIndex, DocumentTitle, EndCharIndex, // StartCharIndex, Type are required. type BetaCitationCharLocationParam struct { - DocumentTitle param.Opt[string] `json:"document_title,omitzero,required"` - CitedText string `json:"cited_text,required"` - DocumentIndex int64 `json:"document_index,required"` - EndCharIndex int64 `json:"end_char_index,required"` - StartCharIndex int64 `json:"start_char_index,required"` + DocumentTitle param.Opt[string] `json:"document_title,omitzero" api:"required"` + CitedText string `json:"cited_text" api:"required"` + DocumentIndex int64 `json:"document_index" api:"required"` + EndCharIndex int64 `json:"end_char_index" api:"required"` + StartCharIndex int64 `json:"start_char_index" api:"required"` // This field can be elided, and will marshal its zero value as "char_location". - Type constant.CharLocation `json:"type,required"` + Type constant.CharLocation `json:"type" api:"required"` paramObj } @@ -868,7 +622,7 @@ func (r *BetaCitationCharLocationParam) UnmarshalJSON(data []byte) error { } type BetaCitationConfig struct { - Enabled bool `json:"enabled,required"` + Enabled bool `json:"enabled" api:"required"` // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. JSON struct { Enabled respjson.Field @@ -884,13 +638,13 @@ func (r *BetaCitationConfig) UnmarshalJSON(data []byte) error { } type BetaCitationContentBlockLocation struct { - CitedText string `json:"cited_text,required"` - DocumentIndex int64 `json:"document_index,required"` - DocumentTitle string `json:"document_title,required"` - EndBlockIndex int64 `json:"end_block_index,required"` - FileID string `json:"file_id,required"` - StartBlockIndex int64 `json:"start_block_index,required"` - Type constant.ContentBlockLocation `json:"type,required"` + CitedText string `json:"cited_text" api:"required"` + DocumentIndex int64 `json:"document_index" api:"required"` + DocumentTitle string `json:"document_title" api:"required"` + EndBlockIndex int64 `json:"end_block_index" api:"required"` + FileID string `json:"file_id" api:"required"` + StartBlockIndex int64 `json:"start_block_index" api:"required"` + Type constant.ContentBlockLocation `json:"type" api:"required"` // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. JSON struct { CitedText respjson.Field @@ -914,14 +668,14 @@ func (r *BetaCitationContentBlockLocation) UnmarshalJSON(data []byte) error { // The properties CitedText, DocumentIndex, DocumentTitle, EndBlockIndex, // StartBlockIndex, Type are required. type BetaCitationContentBlockLocationParam struct { - DocumentTitle param.Opt[string] `json:"document_title,omitzero,required"` - CitedText string `json:"cited_text,required"` - DocumentIndex int64 `json:"document_index,required"` - EndBlockIndex int64 `json:"end_block_index,required"` - StartBlockIndex int64 `json:"start_block_index,required"` + DocumentTitle param.Opt[string] `json:"document_title,omitzero" api:"required"` + CitedText string `json:"cited_text" api:"required"` + DocumentIndex int64 `json:"document_index" api:"required"` + EndBlockIndex int64 `json:"end_block_index" api:"required"` + StartBlockIndex int64 `json:"start_block_index" api:"required"` // This field can be elided, and will marshal its zero value as // "content_block_location". - Type constant.ContentBlockLocation `json:"type,required"` + Type constant.ContentBlockLocation `json:"type" api:"required"` paramObj } @@ -934,13 +688,13 @@ func (r *BetaCitationContentBlockLocationParam) UnmarshalJSON(data []byte) error } type BetaCitationPageLocation struct { - CitedText string `json:"cited_text,required"` - DocumentIndex int64 `json:"document_index,required"` - DocumentTitle string `json:"document_title,required"` - EndPageNumber int64 `json:"end_page_number,required"` - FileID string `json:"file_id,required"` - StartPageNumber int64 `json:"start_page_number,required"` - Type constant.PageLocation `json:"type,required"` + CitedText string `json:"cited_text" api:"required"` + DocumentIndex int64 `json:"document_index" api:"required"` + DocumentTitle string `json:"document_title" api:"required"` + EndPageNumber int64 `json:"end_page_number" api:"required"` + FileID string `json:"file_id" api:"required"` + StartPageNumber int64 `json:"start_page_number" api:"required"` + Type constant.PageLocation `json:"type" api:"required"` // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. JSON struct { CitedText respjson.Field @@ -964,13 +718,13 @@ func (r *BetaCitationPageLocation) UnmarshalJSON(data []byte) error { // The properties CitedText, DocumentIndex, DocumentTitle, EndPageNumber, // StartPageNumber, Type are required. type BetaCitationPageLocationParam struct { - DocumentTitle param.Opt[string] `json:"document_title,omitzero,required"` - CitedText string `json:"cited_text,required"` - DocumentIndex int64 `json:"document_index,required"` - EndPageNumber int64 `json:"end_page_number,required"` - StartPageNumber int64 `json:"start_page_number,required"` + DocumentTitle param.Opt[string] `json:"document_title,omitzero" api:"required"` + CitedText string `json:"cited_text" api:"required"` + DocumentIndex int64 `json:"document_index" api:"required"` + EndPageNumber int64 `json:"end_page_number" api:"required"` + StartPageNumber int64 `json:"start_page_number" api:"required"` // This field can be elided, and will marshal its zero value as "page_location". - Type constant.PageLocation `json:"type,required"` + Type constant.PageLocation `json:"type" api:"required"` paramObj } @@ -983,13 +737,13 @@ func (r *BetaCitationPageLocationParam) UnmarshalJSON(data []byte) error { } type BetaCitationSearchResultLocation struct { - CitedText string `json:"cited_text,required"` - EndBlockIndex int64 `json:"end_block_index,required"` - SearchResultIndex int64 `json:"search_result_index,required"` - Source string `json:"source,required"` - StartBlockIndex int64 `json:"start_block_index,required"` - Title string `json:"title,required"` - Type constant.SearchResultLocation `json:"type,required"` + CitedText string `json:"cited_text" api:"required"` + EndBlockIndex int64 `json:"end_block_index" api:"required"` + SearchResultIndex int64 `json:"search_result_index" api:"required"` + Source string `json:"source" api:"required"` + StartBlockIndex int64 `json:"start_block_index" api:"required"` + Title string `json:"title" api:"required"` + Type constant.SearchResultLocation `json:"type" api:"required"` // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. JSON struct { CitedText respjson.Field @@ -1013,15 +767,15 @@ func (r *BetaCitationSearchResultLocation) UnmarshalJSON(data []byte) error { // The properties CitedText, EndBlockIndex, SearchResultIndex, Source, // StartBlockIndex, Title, Type are required. type BetaCitationSearchResultLocationParam struct { - Title param.Opt[string] `json:"title,omitzero,required"` - CitedText string `json:"cited_text,required"` - EndBlockIndex int64 `json:"end_block_index,required"` - SearchResultIndex int64 `json:"search_result_index,required"` - Source string `json:"source,required"` - StartBlockIndex int64 `json:"start_block_index,required"` + Title param.Opt[string] `json:"title,omitzero" api:"required"` + CitedText string `json:"cited_text" api:"required"` + EndBlockIndex int64 `json:"end_block_index" api:"required"` + SearchResultIndex int64 `json:"search_result_index" api:"required"` + Source string `json:"source" api:"required"` + StartBlockIndex int64 `json:"start_block_index" api:"required"` // This field can be elided, and will marshal its zero value as // "search_result_location". - Type constant.SearchResultLocation `json:"type,required"` + Type constant.SearchResultLocation `json:"type" api:"required"` paramObj } @@ -1035,13 +789,13 @@ func (r *BetaCitationSearchResultLocationParam) UnmarshalJSON(data []byte) error // The properties CitedText, EncryptedIndex, Title, Type, URL are required. type BetaCitationWebSearchResultLocationParam struct { - Title param.Opt[string] `json:"title,omitzero,required"` - CitedText string `json:"cited_text,required"` - EncryptedIndex string `json:"encrypted_index,required"` - URL string `json:"url,required"` + Title param.Opt[string] `json:"title,omitzero" api:"required"` + CitedText string `json:"cited_text" api:"required"` + EncryptedIndex string `json:"encrypted_index" api:"required"` + URL string `json:"url" api:"required"` // This field can be elided, and will marshal its zero value as // "web_search_result_location". - Type constant.WebSearchResultLocation `json:"type,required"` + Type constant.WebSearchResultLocation `json:"type" api:"required"` paramObj } @@ -1067,8 +821,8 @@ func (r *BetaCitationsConfigParam) UnmarshalJSON(data []byte) error { } type BetaCitationsDelta struct { - Citation BetaCitationsDeltaCitationUnion `json:"citation,required"` - Type constant.CitationsDelta `json:"type,required"` + Citation BetaCitationsDeltaCitationUnion `json:"citation" api:"required"` + Type constant.CitationsDelta `json:"type" api:"required"` // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. JSON struct { Citation respjson.Field @@ -1213,11 +967,11 @@ func (r *BetaCitationsDeltaCitationUnion) UnmarshalJSON(data []byte) error { } type BetaCitationsWebSearchResultLocation struct { - CitedText string `json:"cited_text,required"` - EncryptedIndex string `json:"encrypted_index,required"` - Title string `json:"title,required"` - Type constant.WebSearchResultLocation `json:"type,required"` - URL string `json:"url,required"` + CitedText string `json:"cited_text" api:"required"` + EncryptedIndex string `json:"encrypted_index" api:"required"` + Title string `json:"title" api:"required"` + Type constant.WebSearchResultLocation `json:"type" api:"required"` + URL string `json:"url" api:"required"` // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. JSON struct { CitedText respjson.Field @@ -1243,7 +997,7 @@ type BetaClearThinking20251015EditParam struct { Keep BetaClearThinking20251015EditKeepUnionParam `json:"keep,omitzero"` // This field can be elided, and will marshal its zero value as // "clear_thinking_20251015". - Type constant.ClearThinking20251015 `json:"type,required"` + Type constant.ClearThinking20251015 `json:"type" api:"required"` paramObj } @@ -1304,11 +1058,11 @@ func (u BetaClearThinking20251015EditKeepUnionParam) GetType() *string { type BetaClearThinking20251015EditResponse struct { // Number of input tokens cleared by this edit. - ClearedInputTokens int64 `json:"cleared_input_tokens,required"` + ClearedInputTokens int64 `json:"cleared_input_tokens" api:"required"` // Number of thinking turns that were cleared. - ClearedThinkingTurns int64 `json:"cleared_thinking_turns,required"` + ClearedThinkingTurns int64 `json:"cleared_thinking_turns" api:"required"` // The type of context management edit applied. - Type constant.ClearThinking20251015 `json:"type,required"` + Type constant.ClearThinking20251015 `json:"type" api:"required"` // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. JSON struct { ClearedInputTokens respjson.Field @@ -1340,7 +1094,7 @@ type BetaClearToolUses20250919EditParam struct { Trigger BetaClearToolUses20250919EditTriggerUnionParam `json:"trigger,omitzero"` // This field can be elided, and will marshal its zero value as // "clear_tool_uses_20250919". - Type constant.ClearToolUses20250919 `json:"type,required"` + Type constant.ClearToolUses20250919 `json:"type" api:"required"` paramObj } @@ -1364,71 +1118,212 @@ type BetaClearToolUses20250919EditClearToolInputsUnionParam struct { func (u BetaClearToolUses20250919EditClearToolInputsUnionParam) MarshalJSON() ([]byte, error) { return param.MarshalUnion(u, u.OfBool, u.OfStringArray) } -func (u *BetaClearToolUses20250919EditClearToolInputsUnionParam) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, u) +func (u *BetaClearToolUses20250919EditClearToolInputsUnionParam) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, u) +} + +func (u *BetaClearToolUses20250919EditClearToolInputsUnionParam) asAny() any { + if !param.IsOmitted(u.OfBool) { + return &u.OfBool.Value + } else if !param.IsOmitted(u.OfStringArray) { + return &u.OfStringArray + } + return nil +} + +// Only one field can be non-zero. +// +// Use [param.IsOmitted] to confirm if a field is set. +type BetaClearToolUses20250919EditTriggerUnionParam struct { + OfInputTokens *BetaInputTokensTriggerParam `json:",omitzero,inline"` + OfToolUses *BetaToolUsesTriggerParam `json:",omitzero,inline"` + paramUnion +} + +func (u BetaClearToolUses20250919EditTriggerUnionParam) MarshalJSON() ([]byte, error) { + return param.MarshalUnion(u, u.OfInputTokens, u.OfToolUses) +} +func (u *BetaClearToolUses20250919EditTriggerUnionParam) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, u) +} + +func (u *BetaClearToolUses20250919EditTriggerUnionParam) asAny() any { + if !param.IsOmitted(u.OfInputTokens) { + return u.OfInputTokens + } else if !param.IsOmitted(u.OfToolUses) { + return u.OfToolUses + } + return nil +} + +// Returns a pointer to the underlying variant's property, if present. +func (u BetaClearToolUses20250919EditTriggerUnionParam) GetType() *string { + if vt := u.OfInputTokens; vt != nil { + return (*string)(&vt.Type) + } else if vt := u.OfToolUses; vt != nil { + return (*string)(&vt.Type) + } + return nil +} + +// Returns a pointer to the underlying variant's property, if present. +func (u BetaClearToolUses20250919EditTriggerUnionParam) GetValue() *int64 { + if vt := u.OfInputTokens; vt != nil { + return (*int64)(&vt.Value) + } else if vt := u.OfToolUses; vt != nil { + return (*int64)(&vt.Value) + } + return nil +} + +func init() { + apijson.RegisterUnion[BetaClearToolUses20250919EditTriggerUnionParam]( + "type", + apijson.Discriminator[BetaInputTokensTriggerParam]("input_tokens"), + apijson.Discriminator[BetaToolUsesTriggerParam]("tool_uses"), + ) +} + + +func init() { + apijson.RegisterUnion[BetaContentBlockParamUnion]( + "type", + apijson.Discriminator[BetaTextBlockParam]("text"), + apijson.Discriminator[BetaImageBlockParam]("image"), + apijson.Discriminator[BetaRequestDocumentBlockParam]("document"), + apijson.Discriminator[BetaSearchResultBlockParam]("search_result"), + apijson.Discriminator[BetaThinkingBlockParam]("thinking"), + apijson.Discriminator[BetaRedactedThinkingBlockParam]("redacted_thinking"), + apijson.Discriminator[BetaToolUseBlockParam]("tool_use"), + apijson.Discriminator[BetaToolResultBlockParam]("tool_result"), + apijson.Discriminator[BetaServerToolUseBlockParam]("server_tool_use"), + apijson.Discriminator[BetaWebSearchToolResultBlockParam]("web_search_tool_result"), + apijson.Discriminator[BetaWebFetchToolResultBlockParam]("web_fetch_tool_result"), + apijson.Discriminator[BetaCodeExecutionToolResultBlockParam]("code_execution_tool_result"), + apijson.Discriminator[BetaBashCodeExecutionToolResultBlockParam]("bash_code_execution_tool_result"), + apijson.Discriminator[BetaTextEditorCodeExecutionToolResultBlockParam]("text_editor_code_execution_tool_result"), + apijson.Discriminator[BetaToolSearchToolResultBlockParam]("tool_search_tool_result"), + apijson.Discriminator[BetaMCPToolUseBlockParam]("mcp_tool_use"), + apijson.Discriminator[BetaRequestMCPToolResultBlockParam]("mcp_tool_result"), + apijson.Discriminator[BetaContainerUploadBlockParam]("container_upload"), + apijson.Discriminator[BetaCompactionBlockParam]("compaction"), + ) +} + + +func init() { + apijson.RegisterUnion[BetaContextManagementConfigEditUnionParam]( + "type", + apijson.Discriminator[BetaClearToolUses20250919EditParam]("clear_tool_uses_20250919"), + apijson.Discriminator[BetaClearThinking20251015EditParam]("clear_thinking_20251015"), + apijson.Discriminator[BetaCompact20260112EditParam]("compact_20260112"), + ) +} + +func init() { + apijson.RegisterUnion[BetaImageBlockParamSourceUnion]( + "type", + apijson.Discriminator[BetaBase64ImageSourceParam]("base64"), + apijson.Discriminator[BetaURLImageSourceParam]("url"), + apijson.Discriminator[BetaFileImageSourceParam]("file"), + ) +} + +func init() { + apijson.RegisterUnion[BetaRequestDocumentBlockSourceUnionParam]( + "type", + apijson.Discriminator[BetaBase64PDFSourceParam]("base64"), + apijson.Discriminator[BetaPlainTextSourceParam]("text"), + apijson.Discriminator[BetaContentBlockSourceParam]("content"), + apijson.Discriminator[BetaURLPDFSourceParam]("url"), + apijson.Discriminator[BetaFileDocumentSourceParam]("file"), + ) +} + +func init() { + apijson.RegisterUnion[BetaServerToolUseBlockParamCallerUnion]( + "type", + apijson.Discriminator[BetaDirectCallerParam]("direct"), + apijson.Discriminator[BetaServerToolCallerParam]("code_execution_20250825"), + apijson.Discriminator[BetaServerToolCaller20260120Param]("code_execution_20260120"), + ) } -func (u *BetaClearToolUses20250919EditClearToolInputsUnionParam) asAny() any { - if !param.IsOmitted(u.OfBool) { - return &u.OfBool.Value - } else if !param.IsOmitted(u.OfStringArray) { - return &u.OfStringArray - } - return nil +func init() { + apijson.RegisterUnion[BetaTextCitationParamUnion]( + "type", + apijson.Discriminator[BetaCitationCharLocationParam]("char_location"), + apijson.Discriminator[BetaCitationPageLocationParam]("page_location"), + apijson.Discriminator[BetaCitationContentBlockLocationParam]("content_block_location"), + apijson.Discriminator[BetaCitationWebSearchResultLocationParam]("web_search_result_location"), + apijson.Discriminator[BetaCitationSearchResultLocationParam]("search_result_location"), + ) } -// Only one field can be non-zero. -// -// Use [param.IsOmitted] to confirm if a field is set. -type BetaClearToolUses20250919EditTriggerUnionParam struct { - OfInputTokens *BetaInputTokensTriggerParam `json:",omitzero,inline"` - OfToolUses *BetaToolUsesTriggerParam `json:",omitzero,inline"` - paramUnion +func init() { + apijson.RegisterUnion[BetaThinkingConfigParamUnion]( + "type", + apijson.Discriminator[BetaThinkingConfigEnabledParam]("enabled"), + apijson.Discriminator[BetaThinkingConfigDisabledParam]("disabled"), + apijson.Discriminator[BetaThinkingConfigAdaptiveParam]("adaptive"), + ) } -func (u BetaClearToolUses20250919EditTriggerUnionParam) MarshalJSON() ([]byte, error) { - return param.MarshalUnion(u, u.OfInputTokens, u.OfToolUses) +func init() { + apijson.RegisterUnion[BetaToolChoiceUnionParam]( + "type", + apijson.Discriminator[BetaToolChoiceAutoParam]("auto"), + apijson.Discriminator[BetaToolChoiceAnyParam]("any"), + apijson.Discriminator[BetaToolChoiceToolParam]("tool"), + apijson.Discriminator[BetaToolChoiceNoneParam]("none"), + ) } -func (u *BetaClearToolUses20250919EditTriggerUnionParam) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, u) + +func init() { + apijson.RegisterUnion[BetaToolResultBlockParamContentUnion]( + "type", + apijson.Discriminator[BetaTextBlockParam]("text"), + apijson.Discriminator[BetaImageBlockParam]("image"), + apijson.Discriminator[BetaSearchResultBlockParam]("search_result"), + apijson.Discriminator[BetaRequestDocumentBlockParam]("document"), + apijson.Discriminator[BetaToolReferenceBlockParam]("tool_reference"), + ) } -func (u *BetaClearToolUses20250919EditTriggerUnionParam) asAny() any { - if !param.IsOmitted(u.OfInputTokens) { - return u.OfInputTokens - } else if !param.IsOmitted(u.OfToolUses) { - return u.OfToolUses - } - return nil +func init() { + apijson.RegisterUnion[BetaToolUseBlockParamCallerUnion]( + "type", + apijson.Discriminator[BetaDirectCallerParam]("direct"), + apijson.Discriminator[BetaServerToolCallerParam]("code_execution_20250825"), + apijson.Discriminator[BetaServerToolCaller20260120Param]("code_execution_20260120"), + ) } -// Returns a pointer to the underlying variant's property, if present. -func (u BetaClearToolUses20250919EditTriggerUnionParam) GetType() *string { - if vt := u.OfInputTokens; vt != nil { - return (*string)(&vt.Type) - } else if vt := u.OfToolUses; vt != nil { - return (*string)(&vt.Type) - } - return nil +func init() { + apijson.RegisterUnion[BetaWebFetchToolResultBlockParamCallerUnion]( + "type", + apijson.Discriminator[BetaDirectCallerParam]("direct"), + apijson.Discriminator[BetaServerToolCallerParam]("code_execution_20250825"), + apijson.Discriminator[BetaServerToolCaller20260120Param]("code_execution_20260120"), + ) } -// Returns a pointer to the underlying variant's property, if present. -func (u BetaClearToolUses20250919EditTriggerUnionParam) GetValue() *int64 { - if vt := u.OfInputTokens; vt != nil { - return (*int64)(&vt.Value) - } else if vt := u.OfToolUses; vt != nil { - return (*int64)(&vt.Value) - } - return nil +func init() { + apijson.RegisterUnion[BetaWebSearchToolResultBlockParamCallerUnion]( + "type", + apijson.Discriminator[BetaDirectCallerParam]("direct"), + apijson.Discriminator[BetaServerToolCallerParam]("code_execution_20250825"), + apijson.Discriminator[BetaServerToolCaller20260120Param]("code_execution_20260120"), + ) } type BetaClearToolUses20250919EditResponse struct { // Number of input tokens cleared by this edit. - ClearedInputTokens int64 `json:"cleared_input_tokens,required"` + ClearedInputTokens int64 `json:"cleared_input_tokens" api:"required"` // Number of tool uses that were cleared. - ClearedToolUses int64 `json:"cleared_tool_uses,required"` + ClearedToolUses int64 `json:"cleared_tool_uses" api:"required"` // The type of context management edit applied. - Type constant.ClearToolUses20250919 `json:"type,required"` + Type constant.ClearToolUses20250919 `json:"type" api:"required"` // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. JSON struct { ClearedInputTokens respjson.Field @@ -1446,8 +1341,8 @@ func (r *BetaClearToolUses20250919EditResponse) UnmarshalJSON(data []byte) error } type BetaCodeExecutionOutputBlock struct { - FileID string `json:"file_id,required"` - Type constant.CodeExecutionOutput `json:"type,required"` + FileID string `json:"file_id" api:"required"` + Type constant.CodeExecutionOutput `json:"type" api:"required"` // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. JSON struct { FileID respjson.Field @@ -1465,10 +1360,10 @@ func (r *BetaCodeExecutionOutputBlock) UnmarshalJSON(data []byte) error { // The properties FileID, Type are required. type BetaCodeExecutionOutputBlockParam struct { - FileID string `json:"file_id,required"` + FileID string `json:"file_id" api:"required"` // This field can be elided, and will marshal its zero value as // "code_execution_output". - Type constant.CodeExecutionOutput `json:"type,required"` + Type constant.CodeExecutionOutput `json:"type" api:"required"` paramObj } @@ -1481,11 +1376,11 @@ func (r *BetaCodeExecutionOutputBlockParam) UnmarshalJSON(data []byte) error { } type BetaCodeExecutionResultBlock struct { - Content []BetaCodeExecutionOutputBlock `json:"content,required"` - ReturnCode int64 `json:"return_code,required"` - Stderr string `json:"stderr,required"` - Stdout string `json:"stdout,required"` - Type constant.CodeExecutionResult `json:"type,required"` + Content []BetaCodeExecutionOutputBlock `json:"content" api:"required"` + ReturnCode int64 `json:"return_code" api:"required"` + Stderr string `json:"stderr" api:"required"` + Stdout string `json:"stdout" api:"required"` + Type constant.CodeExecutionResult `json:"type" api:"required"` // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. JSON struct { Content respjson.Field @@ -1506,13 +1401,13 @@ func (r *BetaCodeExecutionResultBlock) UnmarshalJSON(data []byte) error { // The properties Content, ReturnCode, Stderr, Stdout, Type are required. type BetaCodeExecutionResultBlockParam struct { - Content []BetaCodeExecutionOutputBlockParam `json:"content,omitzero,required"` - ReturnCode int64 `json:"return_code,required"` - Stderr string `json:"stderr,required"` - Stdout string `json:"stdout,required"` + Content []BetaCodeExecutionOutputBlockParam `json:"content,omitzero" api:"required"` + ReturnCode int64 `json:"return_code" api:"required"` + Stderr string `json:"stderr" api:"required"` + Stdout string `json:"stdout" api:"required"` // This field can be elided, and will marshal its zero value as // "code_execution_result". - Type constant.CodeExecutionResult `json:"type,required"` + Type constant.CodeExecutionResult `json:"type" api:"required"` paramObj } @@ -1540,10 +1435,10 @@ type BetaCodeExecutionTool20250522Param struct { // This is how the tool will be called by the model and in `tool_use` blocks. // // This field can be elided, and will marshal its zero value as "code_execution". - Name constant.CodeExecution `json:"name,required"` + Name constant.CodeExecution `json:"name" api:"required"` // This field can be elided, and will marshal its zero value as // "code_execution_20250522". - Type constant.CodeExecution20250522 `json:"type,required"` + Type constant.CodeExecution20250522 `json:"type" api:"required"` paramObj } @@ -1571,10 +1466,10 @@ type BetaCodeExecutionTool20250825Param struct { // This is how the tool will be called by the model and in `tool_use` blocks. // // This field can be elided, and will marshal its zero value as "code_execution". - Name constant.CodeExecution `json:"name,required"` + Name constant.CodeExecution `json:"name" api:"required"` // This field can be elided, and will marshal its zero value as // "code_execution_20250825". - Type constant.CodeExecution20250825 `json:"type,required"` + Type constant.CodeExecution20250825 `json:"type" api:"required"` paramObj } @@ -1605,10 +1500,10 @@ type BetaCodeExecutionTool20260120Param struct { // This is how the tool will be called by the model and in `tool_use` blocks. // // This field can be elided, and will marshal its zero value as "code_execution". - Name constant.CodeExecution `json:"name,required"` + Name constant.CodeExecution `json:"name" api:"required"` // This field can be elided, and will marshal its zero value as // "code_execution_20260120". - Type constant.CodeExecution20260120 `json:"type,required"` + Type constant.CodeExecution20260120 `json:"type" api:"required"` paramObj } @@ -1622,9 +1517,9 @@ func (r *BetaCodeExecutionTool20260120Param) UnmarshalJSON(data []byte) error { type BetaCodeExecutionToolResultBlock struct { // Code execution result with encrypted stdout for PFC + web_search results. - Content BetaCodeExecutionToolResultBlockContentUnion `json:"content,required"` - ToolUseID string `json:"tool_use_id,required"` - Type constant.CodeExecutionToolResult `json:"type,required"` + Content BetaCodeExecutionToolResultBlockContentUnion `json:"content" api:"required"` + ToolUseID string `json:"tool_use_id" api:"required"` + Type constant.CodeExecutionToolResult `json:"type" api:"required"` // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. JSON struct { Content respjson.Field @@ -1694,13 +1589,13 @@ func (r *BetaCodeExecutionToolResultBlockContentUnion) UnmarshalJSON(data []byte // The properties Content, ToolUseID, Type are required. type BetaCodeExecutionToolResultBlockParam struct { // Code execution result with encrypted stdout for PFC + web_search results. - Content BetaCodeExecutionToolResultBlockParamContentUnion `json:"content,omitzero,required"` - ToolUseID string `json:"tool_use_id,required"` + Content BetaCodeExecutionToolResultBlockParamContentUnion `json:"content,omitzero" api:"required"` + ToolUseID string `json:"tool_use_id" api:"required"` // Create a cache control breakpoint at this content block. CacheControl BetaCacheControlEphemeralParam `json:"cache_control,omitzero"` // This field can be elided, and will marshal its zero value as // "code_execution_tool_result". - Type constant.CodeExecutionToolResult `json:"type,required"` + Type constant.CodeExecutionToolResult `json:"type" api:"required"` paramObj } @@ -1815,8 +1710,8 @@ func (u BetaCodeExecutionToolResultBlockParamContentUnion) GetContent() []BetaCo type BetaCodeExecutionToolResultError struct { // Any of "invalid_tool_input", "unavailable", "too_many_requests", // "execution_time_exceeded". - ErrorCode BetaCodeExecutionToolResultErrorCode `json:"error_code,required"` - Type constant.CodeExecutionToolResultError `json:"type,required"` + ErrorCode BetaCodeExecutionToolResultErrorCode `json:"error_code" api:"required"` + Type constant.CodeExecutionToolResultError `json:"type" api:"required"` // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. JSON struct { ErrorCode respjson.Field @@ -1845,10 +1740,10 @@ const ( type BetaCodeExecutionToolResultErrorParam struct { // Any of "invalid_tool_input", "unavailable", "too_many_requests", // "execution_time_exceeded". - ErrorCode BetaCodeExecutionToolResultErrorCode `json:"error_code,omitzero,required"` + ErrorCode BetaCodeExecutionToolResultErrorCode `json:"error_code,omitzero" api:"required"` // This field can be elided, and will marshal its zero value as // "code_execution_tool_result_error". - Type constant.CodeExecutionToolResultError `json:"type,required"` + Type constant.CodeExecutionToolResultError `json:"type" api:"required"` paramObj } @@ -1872,7 +1767,7 @@ type BetaCompact20260112EditParam struct { // When to trigger compaction. Defaults to 150000 input tokens. Trigger BetaInputTokensTriggerParam `json:"trigger,omitzero"` // This field can be elided, and will marshal its zero value as "compact_20260112". - Type constant.Compact20260112 `json:"type,required"` + Type constant.Compact20260112 `json:"type" api:"required"` paramObj } @@ -1891,8 +1786,8 @@ func (r *BetaCompact20260112EditParam) UnmarshalJSON(data []byte) error { // compaction blocks with null content; the server treats them as no-ops. type BetaCompactionBlock struct { // Summary of compacted content, or null if compaction failed - Content string `json:"content,required"` - Type constant.Compaction `json:"type,required"` + Content string `json:"content" api:"required"` + Type constant.Compaction `json:"type" api:"required"` // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. JSON struct { Content respjson.Field @@ -1919,11 +1814,11 @@ func (r *BetaCompactionBlock) UnmarshalJSON(data []byte) error { // The properties Content, Type are required. type BetaCompactionBlockParam struct { // Summary of previously compacted content, or null if compaction failed - Content param.Opt[string] `json:"content,omitzero,required"` + Content param.Opt[string] `json:"content,omitzero" api:"required"` // Create a cache control breakpoint at this content block. CacheControl BetaCacheControlEphemeralParam `json:"cache_control,omitzero"` // This field can be elided, and will marshal its zero value as "compaction". - Type constant.Compaction `json:"type,required"` + Type constant.Compaction `json:"type" api:"required"` paramObj } @@ -1936,8 +1831,8 @@ func (r *BetaCompactionBlockParam) UnmarshalJSON(data []byte) error { } type BetaCompactionContentBlockDelta struct { - Content string `json:"content,required"` - Type constant.CompactionDelta `json:"type,required"` + Content string `json:"content" api:"required"` + Type constant.CompactionDelta `json:"type" api:"required"` // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. JSON struct { Content respjson.Field @@ -1956,17 +1851,17 @@ func (r *BetaCompactionContentBlockDelta) UnmarshalJSON(data []byte) error { // Token usage for a compaction iteration. type BetaCompactionIterationUsage struct { // Breakdown of cached tokens by TTL - CacheCreation BetaCacheCreation `json:"cache_creation,required"` + CacheCreation BetaCacheCreation `json:"cache_creation" api:"required"` // The number of input tokens used to create the cache entry. - CacheCreationInputTokens int64 `json:"cache_creation_input_tokens,required"` + CacheCreationInputTokens int64 `json:"cache_creation_input_tokens" api:"required"` // The number of input tokens read from the cache. - CacheReadInputTokens int64 `json:"cache_read_input_tokens,required"` + CacheReadInputTokens int64 `json:"cache_read_input_tokens" api:"required"` // The number of input tokens which were used. - InputTokens int64 `json:"input_tokens,required"` + InputTokens int64 `json:"input_tokens" api:"required"` // The number of output tokens which were used. - OutputTokens int64 `json:"output_tokens,required"` + OutputTokens int64 `json:"output_tokens" api:"required"` // Usage for a compaction iteration - Type constant.Compaction `json:"type,required"` + Type constant.Compaction `json:"type" api:"required"` // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. JSON struct { CacheCreation respjson.Field @@ -1990,11 +1885,11 @@ func (r *BetaCompactionIterationUsage) UnmarshalJSON(data []byte) error { // tool) type BetaContainer struct { // Identifier for the container used in this request - ID string `json:"id,required"` + ID string `json:"id" api:"required"` // The time at which the container will expire. - ExpiresAt time.Time `json:"expires_at,required" format:"date-time"` + ExpiresAt time.Time `json:"expires_at" api:"required" format:"date-time"` // Skills loaded in the container - Skills []BetaSkill `json:"skills,required"` + Skills []BetaSkill `json:"skills" api:"required"` // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. JSON struct { ID respjson.Field @@ -2030,8 +1925,8 @@ func (r *BetaContainerParams) UnmarshalJSON(data []byte) error { // Response model for a file uploaded to the container. type BetaContainerUploadBlock struct { - FileID string `json:"file_id,required"` - Type constant.ContainerUpload `json:"type,required"` + FileID string `json:"file_id" api:"required"` + Type constant.ContainerUpload `json:"type" api:"required"` // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. JSON struct { FileID respjson.Field @@ -2052,11 +1947,11 @@ func (r *BetaContainerUploadBlock) UnmarshalJSON(data []byte) error { // // The properties FileID, Type are required. type BetaContainerUploadBlockParam struct { - FileID string `json:"file_id,required"` + FileID string `json:"file_id" api:"required"` // Create a cache control breakpoint at this content block. CacheControl BetaCacheControlEphemeralParam `json:"cache_control,omitzero"` // This field can be elided, and will marshal its zero value as "container_upload". - Type constant.ContainerUpload `json:"type,required"` + Type constant.ContainerUpload `json:"type" api:"required"` paramObj } @@ -3478,12 +3373,11 @@ func (u betaContentBlockParamUnionCaller) GetToolID() *string { return nil } - // The properties Content, Type are required. type BetaContentBlockSourceParam struct { - Content BetaContentBlockSourceContentUnionParam `json:"content,omitzero,required"` + Content BetaContentBlockSourceContentUnionParam `json:"content,omitzero" api:"required"` // This field can be elided, and will marshal its zero value as "content". - Type constant.Content `json:"type,required"` + Type constant.Content `json:"type" api:"required"` paramObj } @@ -3661,10 +3555,9 @@ func (u betaContextManagementConfigEditUnionParamKeep) GetValue() *int64 { return nil } - type BetaContextManagementResponse struct { // List of context management edits that were applied. - AppliedEdits []BetaContextManagementResponseAppliedEditUnion `json:"applied_edits,required"` + AppliedEdits []BetaContextManagementResponseAppliedEditUnion `json:"applied_edits" api:"required"` // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. JSON struct { AppliedEdits respjson.Field @@ -3751,7 +3644,7 @@ func (r *BetaContextManagementResponseAppliedEditUnion) UnmarshalJSON(data []byt type BetaCountTokensContextManagementResponse struct { // The original token count before context management was applied - OriginalInputTokens int64 `json:"original_input_tokens,required"` + OriginalInputTokens int64 `json:"original_input_tokens" api:"required"` // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. JSON struct { OriginalInputTokens respjson.Field @@ -3768,7 +3661,7 @@ func (r *BetaCountTokensContextManagementResponse) UnmarshalJSON(data []byte) er // Tool invocation directly from the model. type BetaDirectCaller struct { - Type constant.Direct `json:"type,required"` + Type constant.Direct `json:"type" api:"required"` // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. JSON struct { Type respjson.Field @@ -3802,7 +3695,7 @@ func NewBetaDirectCallerParam() BetaDirectCallerParam { // // This struct has a constant value, construct it with [NewBetaDirectCallerParam]. type BetaDirectCallerParam struct { - Type constant.Direct `json:"type,required"` + Type constant.Direct `json:"type" api:"required"` paramObj } @@ -3816,11 +3709,11 @@ func (r *BetaDirectCallerParam) UnmarshalJSON(data []byte) error { type BetaDocumentBlock struct { // Citation configuration for the document - Citations BetaCitationConfig `json:"citations,required"` - Source BetaDocumentBlockSourceUnion `json:"source,required"` + Citations BetaCitationConfig `json:"citations" api:"required"` + Source BetaDocumentBlockSourceUnion `json:"source" api:"required"` // The title of the document - Title string `json:"title,required"` - Type constant.Document `json:"type,required"` + Title string `json:"title" api:"required"` + Type constant.Document `json:"type" api:"required"` // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. JSON struct { Citations respjson.Field @@ -3904,11 +3797,11 @@ func (r *BetaDocumentBlockSourceUnion) UnmarshalJSON(data []byte) error { // Code execution result with encrypted stdout for PFC + web_search results. type BetaEncryptedCodeExecutionResultBlock struct { - Content []BetaCodeExecutionOutputBlock `json:"content,required"` - EncryptedStdout string `json:"encrypted_stdout,required"` - ReturnCode int64 `json:"return_code,required"` - Stderr string `json:"stderr,required"` - Type constant.EncryptedCodeExecutionResult `json:"type,required"` + Content []BetaCodeExecutionOutputBlock `json:"content" api:"required"` + EncryptedStdout string `json:"encrypted_stdout" api:"required"` + ReturnCode int64 `json:"return_code" api:"required"` + Stderr string `json:"stderr" api:"required"` + Type constant.EncryptedCodeExecutionResult `json:"type" api:"required"` // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. JSON struct { Content respjson.Field @@ -3931,13 +3824,13 @@ func (r *BetaEncryptedCodeExecutionResultBlock) UnmarshalJSON(data []byte) error // // The properties Content, EncryptedStdout, ReturnCode, Stderr, Type are required. type BetaEncryptedCodeExecutionResultBlockParam struct { - Content []BetaCodeExecutionOutputBlockParam `json:"content,omitzero,required"` - EncryptedStdout string `json:"encrypted_stdout,required"` - ReturnCode int64 `json:"return_code,required"` - Stderr string `json:"stderr,required"` + Content []BetaCodeExecutionOutputBlockParam `json:"content,omitzero" api:"required"` + EncryptedStdout string `json:"encrypted_stdout" api:"required"` + ReturnCode int64 `json:"return_code" api:"required"` + Stderr string `json:"stderr" api:"required"` // This field can be elided, and will marshal its zero value as // "encrypted_code_execution_result". - Type constant.EncryptedCodeExecutionResult `json:"type,required"` + Type constant.EncryptedCodeExecutionResult `json:"type" api:"required"` paramObj } @@ -3951,9 +3844,9 @@ func (r *BetaEncryptedCodeExecutionResultBlockParam) UnmarshalJSON(data []byte) // The properties FileID, Type are required. type BetaFileDocumentSourceParam struct { - FileID string `json:"file_id,required"` + FileID string `json:"file_id" api:"required"` // This field can be elided, and will marshal its zero value as "file". - Type constant.File `json:"type,required"` + Type constant.File `json:"type" api:"required"` paramObj } @@ -3967,9 +3860,9 @@ func (r *BetaFileDocumentSourceParam) UnmarshalJSON(data []byte) error { // The properties FileID, Type are required. type BetaFileImageSourceParam struct { - FileID string `json:"file_id,required"` + FileID string `json:"file_id" api:"required"` // This field can be elided, and will marshal its zero value as "file". - Type constant.File `json:"type,required"` + Type constant.File `json:"type" api:"required"` paramObj } @@ -3983,11 +3876,11 @@ func (r *BetaFileImageSourceParam) UnmarshalJSON(data []byte) error { // The properties Source, Type are required. type BetaImageBlockParam struct { - Source BetaImageBlockParamSourceUnion `json:"source,omitzero,required"` + Source BetaImageBlockParamSourceUnion `json:"source,omitzero" api:"required"` // Create a cache control breakpoint at this content block. CacheControl BetaCacheControlEphemeralParam `json:"cache_control,omitzero"` // This field can be elided, and will marshal its zero value as "image". - Type constant.Image `json:"type,required"` + Type constant.Image `json:"type" api:"required"` paramObj } @@ -4072,8 +3965,8 @@ func (u BetaImageBlockParamSourceUnion) GetType() *string { } type BetaInputJSONDelta struct { - PartialJSON string `json:"partial_json,required"` - Type constant.InputJSONDelta `json:"type,required"` + PartialJSON string `json:"partial_json" api:"required"` + Type constant.InputJSONDelta `json:"type" api:"required"` // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. JSON struct { PartialJSON respjson.Field @@ -4091,9 +3984,9 @@ func (r *BetaInputJSONDelta) UnmarshalJSON(data []byte) error { // The properties Type, Value are required. type BetaInputTokensClearAtLeastParam struct { - Value int64 `json:"value,required"` + Value int64 `json:"value" api:"required"` // This field can be elided, and will marshal its zero value as "input_tokens". - Type constant.InputTokens `json:"type,required"` + Type constant.InputTokens `json:"type" api:"required"` paramObj } @@ -4107,9 +4000,9 @@ func (r *BetaInputTokensClearAtLeastParam) UnmarshalJSON(data []byte) error { // The properties Type, Value are required. type BetaInputTokensTriggerParam struct { - Value int64 `json:"value,required"` + Value int64 `json:"value" api:"required"` // This field can be elided, and will marshal its zero value as "input_tokens". - Type constant.InputTokens `json:"type,required"` + Type constant.InputTokens `json:"type" api:"required"` paramObj } @@ -4126,6 +4019,8 @@ type BetaIterationsUsage []BetaIterationsUsageItemUnion // BetaIterationsUsageItemUnion contains all possible properties and values from // [BetaMessageIterationUsage], [BetaCompactionIterationUsage]. // +// Use the [BetaIterationsUsageItemUnion.AsAny] method to switch on the variant. +// // Use the methods beginning with 'As' to cast the union to one of its variants. type BetaIterationsUsageItemUnion struct { // This field is from variant [BetaMessageIterationUsage]. @@ -4134,8 +4029,9 @@ type BetaIterationsUsageItemUnion struct { CacheReadInputTokens int64 `json:"cache_read_input_tokens"` InputTokens int64 `json:"input_tokens"` OutputTokens int64 `json:"output_tokens"` - Type string `json:"type"` - JSON struct { + // Any of "message", "compaction". + Type string `json:"type"` + JSON struct { CacheCreation respjson.Field CacheCreationInputTokens respjson.Field CacheReadInputTokens respjson.Field @@ -4146,12 +4042,40 @@ type BetaIterationsUsageItemUnion struct { } `json:"-"` } -func (u BetaIterationsUsageItemUnion) AsMessageIterationUsage() (v BetaMessageIterationUsage) { +// anyBetaIterationsUsageItem is implemented by each variant of +// [BetaIterationsUsageItemUnion] to add type safety for the return type of +// [BetaIterationsUsageItemUnion.AsAny] +type anyBetaIterationsUsageItem interface { + implBetaIterationsUsageItemUnion() +} + +func (BetaMessageIterationUsage) implBetaIterationsUsageItemUnion() {} +func (BetaCompactionIterationUsage) implBetaIterationsUsageItemUnion() {} + +// Use the following switch statement to find the correct variant +// +// switch variant := BetaIterationsUsageItemUnion.AsAny().(type) { +// case anthropic.BetaMessageIterationUsage: +// case anthropic.BetaCompactionIterationUsage: +// default: +// fmt.Errorf("no variant present") +// } +func (u BetaIterationsUsageItemUnion) AsAny() anyBetaIterationsUsageItem { + switch u.Type { + case "message": + return u.AsMessage() + case "compaction": + return u.AsCompaction() + } + return nil +} + +func (u BetaIterationsUsageItemUnion) AsMessage() (v BetaMessageIterationUsage) { apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) return } -func (u BetaIterationsUsageItemUnion) AsCompactionIterationUsage() (v BetaCompactionIterationUsage) { +func (u BetaIterationsUsageItemUnion) AsCompaction() (v BetaCompactionIterationUsage) { apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) return } @@ -4166,9 +4090,9 @@ func (r *BetaIterationsUsageItemUnion) UnmarshalJSON(data []byte) error { // The properties Schema, Type are required. type BetaJSONOutputFormatParam struct { // The JSON schema of the format - Schema map[string]any `json:"schema,omitzero,required"` + Schema map[string]any `json:"schema,omitzero" api:"required"` // This field can be elided, and will marshal its zero value as "json_schema". - Type constant.JSONSchema `json:"type,required"` + Type constant.JSONSchema `json:"type" api:"required"` paramObj } @@ -4211,10 +4135,10 @@ func (r *BetaMCPToolDefaultConfigParam) UnmarshalJSON(data []byte) error { } type BetaMCPToolResultBlock struct { - Content BetaMCPToolResultBlockContentUnion `json:"content,required"` - IsError bool `json:"is_error,required"` - ToolUseID string `json:"tool_use_id,required"` - Type constant.MCPToolResult `json:"type,required"` + Content BetaMCPToolResultBlockContentUnion `json:"content" api:"required"` + IsError bool `json:"is_error" api:"required"` + ToolUseID string `json:"tool_use_id" api:"required"` + Type constant.MCPToolResult `json:"type" api:"required"` // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. JSON struct { Content respjson.Field @@ -4270,13 +4194,13 @@ func (r *BetaMCPToolResultBlockContentUnion) UnmarshalJSON(data []byte) error { } type BetaMCPToolUseBlock struct { - ID string `json:"id,required"` - Input any `json:"input,required"` + ID string `json:"id" api:"required"` + Input any `json:"input" api:"required"` // The name of the MCP tool - Name string `json:"name,required"` + Name string `json:"name" api:"required"` // The name of the MCP server - ServerName string `json:"server_name,required"` - Type constant.MCPToolUse `json:"type,required"` + ServerName string `json:"server_name" api:"required"` + Type constant.MCPToolUse `json:"type" api:"required"` // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. JSON struct { ID respjson.Field @@ -4297,15 +4221,15 @@ func (r *BetaMCPToolUseBlock) UnmarshalJSON(data []byte) error { // The properties ID, Input, Name, ServerName, Type are required. type BetaMCPToolUseBlockParam struct { - ID string `json:"id,required"` - Input any `json:"input,omitzero,required"` - Name string `json:"name,required"` + ID string `json:"id" api:"required"` + Input any `json:"input,omitzero" api:"required"` + Name string `json:"name" api:"required"` // The name of the MCP server - ServerName string `json:"server_name,required"` + ServerName string `json:"server_name" api:"required"` // Create a cache control breakpoint at this content block. CacheControl BetaCacheControlEphemeralParam `json:"cache_control,omitzero"` // This field can be elided, and will marshal its zero value as "mcp_tool_use". - Type constant.MCPToolUse `json:"type,required"` + Type constant.MCPToolUse `json:"type" api:"required"` paramObj } @@ -4325,7 +4249,7 @@ func (r *BetaMCPToolUseBlockParam) UnmarshalJSON(data []byte) error { // The properties MCPServerName, Type are required. type BetaMCPToolsetParam struct { // Name of the MCP server to configure tools for - MCPServerName string `json:"mcp_server_name,required"` + MCPServerName string `json:"mcp_server_name" api:"required"` // Configuration overrides for specific tools, keyed by tool name Configs map[string]BetaMCPToolConfigParam `json:"configs,omitzero"` // Create a cache control breakpoint at this content block. @@ -4333,7 +4257,7 @@ type BetaMCPToolsetParam struct { // Default configuration applied to all tools from this server DefaultConfig BetaMCPToolDefaultConfigParam `json:"default_config,omitzero"` // This field can be elided, and will marshal its zero value as "mcp_toolset". - Type constant.MCPToolset `json:"type,required"` + Type constant.MCPToolset `json:"type" api:"required"` paramObj } @@ -4362,9 +4286,9 @@ type BetaMemoryTool20250818Param struct { // This is how the tool will be called by the model and in `tool_use` blocks. // // This field can be elided, and will marshal its zero value as "memory". - Name constant.Memory `json:"name,required"` + Name constant.Memory `json:"name" api:"required"` // This field can be elided, and will marshal its zero value as "memory_20250818". - Type constant.Memory20250818 `json:"type,required"` + Type constant.Memory20250818 `json:"type" api:"required"` paramObj } @@ -4504,11 +4428,11 @@ func (r *BetaMemoryTool20250818CommandUnion) UnmarshalJSON(data []byte) error { type BetaMemoryTool20250818CreateCommand struct { // Command type identifier - Command constant.Create `json:"command,required"` + Command constant.Create `json:"command" api:"required"` // Content to write to the file - FileText string `json:"file_text,required"` + FileText string `json:"file_text" api:"required"` // Path where the file should be created - Path string `json:"path,required"` + Path string `json:"path" api:"required"` // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. JSON struct { Command respjson.Field @@ -4527,9 +4451,9 @@ func (r *BetaMemoryTool20250818CreateCommand) UnmarshalJSON(data []byte) error { type BetaMemoryTool20250818DeleteCommand struct { // Command type identifier - Command constant.Delete `json:"command,required"` + Command constant.Delete `json:"command" api:"required"` // Path to the file or directory to delete - Path string `json:"path,required"` + Path string `json:"path" api:"required"` // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. JSON struct { Command respjson.Field @@ -4547,13 +4471,13 @@ func (r *BetaMemoryTool20250818DeleteCommand) UnmarshalJSON(data []byte) error { type BetaMemoryTool20250818InsertCommand struct { // Command type identifier - Command constant.Insert `json:"command,required"` + Command constant.Insert `json:"command" api:"required"` // Line number where text should be inserted - InsertLine int64 `json:"insert_line,required"` + InsertLine int64 `json:"insert_line" api:"required"` // Text to insert at the specified line - InsertText string `json:"insert_text,required"` + InsertText string `json:"insert_text" api:"required"` // Path to the file where text should be inserted - Path string `json:"path,required"` + Path string `json:"path" api:"required"` // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. JSON struct { Command respjson.Field @@ -4573,11 +4497,11 @@ func (r *BetaMemoryTool20250818InsertCommand) UnmarshalJSON(data []byte) error { type BetaMemoryTool20250818RenameCommand struct { // Command type identifier - Command constant.Rename `json:"command,required"` + Command constant.Rename `json:"command" api:"required"` // New path for the file or directory - NewPath string `json:"new_path,required"` + NewPath string `json:"new_path" api:"required"` // Current path of the file or directory - OldPath string `json:"old_path,required"` + OldPath string `json:"old_path" api:"required"` // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. JSON struct { Command respjson.Field @@ -4596,13 +4520,13 @@ func (r *BetaMemoryTool20250818RenameCommand) UnmarshalJSON(data []byte) error { type BetaMemoryTool20250818StrReplaceCommand struct { // Command type identifier - Command constant.StrReplace `json:"command,required"` + Command constant.StrReplace `json:"command" api:"required"` // Text to replace with - NewStr string `json:"new_str,required"` + NewStr string `json:"new_str" api:"required"` // Text to search for and replace - OldStr string `json:"old_str,required"` + OldStr string `json:"old_str" api:"required"` // Path to the file where text should be replaced - Path string `json:"path,required"` + Path string `json:"path" api:"required"` // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. JSON struct { Command respjson.Field @@ -4622,9 +4546,9 @@ func (r *BetaMemoryTool20250818StrReplaceCommand) UnmarshalJSON(data []byte) err type BetaMemoryTool20250818ViewCommand struct { // Command type identifier - Command constant.View `json:"command,required"` + Command constant.View `json:"command" api:"required"` // Path to directory or file to view - Path string `json:"path,required"` + Path string `json:"path" api:"required"` // Optional line range for viewing specific lines ViewRange []int64 `json:"view_range"` // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. @@ -4647,10 +4571,10 @@ type BetaMessage struct { // Unique object identifier. // // The format and length of IDs may change over time. - ID string `json:"id,required"` + ID string `json:"id" api:"required"` // Information about the container used in the request (for the code execution // tool) - Container BetaContainer `json:"container,required"` + Container BetaContainer `json:"container" api:"required"` // Content generated by the model. // // This is an array of content blocks, each of which has a `type` that determines @@ -4685,19 +4609,19 @@ type BetaMessage struct { // ```json // [{ "type": "text", "text": "B)" }] // ``` - Content []BetaContentBlockUnion `json:"content,required"` + Content []BetaContentBlockUnion `json:"content" api:"required"` // Context management response. // // Information about context management strategies applied during the request. - ContextManagement BetaContextManagementResponse `json:"context_management,required"` + ContextManagement BetaContextManagementResponse `json:"context_management" api:"required"` // The model that will complete your prompt.\n\nSee // [models](https://docs.anthropic.com/en/docs/models-overview) for additional // details and options. - Model Model `json:"model,required"` + Model Model `json:"model" api:"required"` // Conversational role of the generated message. // // This will always be `"assistant"`. - Role constant.Assistant `json:"role,required"` + Role constant.Assistant `json:"role" api:"required"` // The reason that we stopped. // // This may be one the following values: @@ -4716,16 +4640,16 @@ type BetaMessage struct { // // Any of "end_turn", "max_tokens", "stop_sequence", "tool_use", "pause_turn", // "compaction", "refusal", "model_context_window_exceeded". - StopReason BetaStopReason `json:"stop_reason,required"` + StopReason BetaStopReason `json:"stop_reason" api:"required"` // Which custom stop sequence was generated, if any. // // This value will be a non-null string if one of your custom stop sequences was // generated. - StopSequence string `json:"stop_sequence,required"` + StopSequence string `json:"stop_sequence" api:"required"` // Object type. // // For Messages, this is always `"message"`. - Type constant.Message `json:"type,required"` + Type constant.Message `json:"type" api:"required"` // Billing and rate-limit usage. // // Anthropic's API bills and rate-limits by token counts, as tokens represent the @@ -4741,7 +4665,7 @@ type BetaMessage struct { // // Total input tokens in a request is the summation of `input_tokens`, // `cache_creation_input_tokens`, and `cache_read_input_tokens`. - Usage BetaUsage `json:"usage,required"` + Usage BetaUsage `json:"usage" api:"required"` // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. JSON struct { ID respjson.Field @@ -4765,33 +4689,14 @@ func (r *BetaMessage) UnmarshalJSON(data []byte) error { return apijson.UnmarshalRoot(data, r) } -// The reason that we stopped. -// -// This may be one the following values: -// -// - `"end_turn"`: the model reached a natural stopping point -// - `"max_tokens"`: we exceeded the requested `max_tokens` or the model's maximum -// - `"stop_sequence"`: one of your provided custom `stop_sequences` was generated -// - `"tool_use"`: the model invoked one or more tools -// -// In non-streaming mode this value is always non-null. In streaming mode, it is -// null in the `message_start` event and non-null otherwise. -type BetaMessageStopReason string - -const ( - BetaMessageStopReasonEndTurn BetaMessageStopReason = "end_turn" - BetaMessageStopReasonMaxTokens BetaMessageStopReason = "max_tokens" - BetaMessageStopReasonStopSequence BetaMessageStopReason = "stop_sequence" - BetaMessageStopReasonToolUse BetaMessageStopReason = "tool_use" -) type BetaMessageDeltaUsage struct { // The cumulative number of input tokens used to create the cache entry. - CacheCreationInputTokens int64 `json:"cache_creation_input_tokens,required"` + CacheCreationInputTokens int64 `json:"cache_creation_input_tokens" api:"required"` // The cumulative number of input tokens read from the cache. - CacheReadInputTokens int64 `json:"cache_read_input_tokens,required"` + CacheReadInputTokens int64 `json:"cache_read_input_tokens" api:"required"` // The cumulative number of input tokens which were used. - InputTokens int64 `json:"input_tokens,required"` + InputTokens int64 `json:"input_tokens" api:"required"` // Per-iteration token usage breakdown. // // Each entry represents one sampling iteration, with its own input/output token @@ -4800,11 +4705,11 @@ type BetaMessageDeltaUsage struct { // - Determine which iterations exceeded long context thresholds (>=200k tokens) // - Calculate the true context window size from the last iteration // - Understand token accumulation across server-side tool use loops - Iterations BetaIterationsUsage `json:"iterations,required"` + Iterations BetaIterationsUsage `json:"iterations" api:"required"` // The cumulative number of output tokens which were used. - OutputTokens int64 `json:"output_tokens,required"` + OutputTokens int64 `json:"output_tokens" api:"required"` // The number of server tool requests. - ServerToolUse BetaServerToolUsage `json:"server_tool_use,required"` + ServerToolUse BetaServerToolUsage `json:"server_tool_use" api:"required"` // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. JSON struct { CacheCreationInputTokens respjson.Field @@ -4827,17 +4732,17 @@ func (r *BetaMessageDeltaUsage) UnmarshalJSON(data []byte) error { // Token usage for a sampling iteration. type BetaMessageIterationUsage struct { // Breakdown of cached tokens by TTL - CacheCreation BetaCacheCreation `json:"cache_creation,required"` + CacheCreation BetaCacheCreation `json:"cache_creation" api:"required"` // The number of input tokens used to create the cache entry. - CacheCreationInputTokens int64 `json:"cache_creation_input_tokens,required"` + CacheCreationInputTokens int64 `json:"cache_creation_input_tokens" api:"required"` // The number of input tokens read from the cache. - CacheReadInputTokens int64 `json:"cache_read_input_tokens,required"` + CacheReadInputTokens int64 `json:"cache_read_input_tokens" api:"required"` // The number of input tokens which were used. - InputTokens int64 `json:"input_tokens,required"` + InputTokens int64 `json:"input_tokens" api:"required"` // The number of output tokens which were used. - OutputTokens int64 `json:"output_tokens,required"` + OutputTokens int64 `json:"output_tokens" api:"required"` // Usage for a sampling iteration - Type constant.Message `json:"type,required"` + Type constant.Message `json:"type" api:"required"` // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. JSON struct { CacheCreation respjson.Field @@ -4859,9 +4764,9 @@ func (r *BetaMessageIterationUsage) UnmarshalJSON(data []byte) error { // The properties Content, Role are required. type BetaMessageParam struct { - Content []BetaContentBlockParamUnion `json:"content,omitzero,required"` + Content []BetaContentBlockParamUnion `json:"content,omitzero" api:"required"` // Any of "user", "assistant". - Role BetaMessageParamRole `json:"role,omitzero,required"` + Role BetaMessageParamRole `json:"role,omitzero" api:"required"` paramObj } @@ -4889,10 +4794,10 @@ const ( type BetaMessageTokensCount struct { // Information about context management applied to the message. - ContextManagement BetaCountTokensContextManagementResponse `json:"context_management,required"` + ContextManagement BetaCountTokensContextManagementResponse `json:"context_management" api:"required"` // The total number of tokens across the provided list of messages, system prompt, // and tools. - InputTokens int64 `json:"input_tokens,required"` + InputTokens int64 `json:"input_tokens" api:"required"` // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. JSON struct { ContextManagement respjson.Field @@ -4956,9 +4861,9 @@ const ( ) type BetaPlainTextSource struct { - Data string `json:"data,required"` - MediaType constant.TextPlain `json:"media_type,required"` - Type constant.Text `json:"type,required"` + Data string `json:"data" api:"required"` + MediaType constant.TextPlain `json:"media_type" api:"required"` + Type constant.Text `json:"type" api:"required"` // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. JSON struct { Data respjson.Field @@ -4986,11 +4891,11 @@ func (r BetaPlainTextSource) ToParam() BetaPlainTextSourceParam { // The properties Data, MediaType, Type are required. type BetaPlainTextSourceParam struct { - Data string `json:"data,required"` + Data string `json:"data" api:"required"` // This field can be elided, and will marshal its zero value as "text/plain". - MediaType constant.TextPlain `json:"media_type,required"` + MediaType constant.TextPlain `json:"media_type" api:"required"` // This field can be elided, and will marshal its zero value as "text". - Type constant.Text `json:"type,required"` + Type constant.Text `json:"type" api:"required"` paramObj } @@ -5119,9 +5024,9 @@ func (r *BetaRawContentBlockDeltaUnion) UnmarshalJSON(data []byte) error { } type BetaRawContentBlockDeltaEvent struct { - Delta BetaRawContentBlockDeltaUnion `json:"delta,required"` - Index int64 `json:"index,required"` - Type constant.ContentBlockDelta `json:"type,required"` + Delta BetaRawContentBlockDeltaUnion `json:"delta" api:"required"` + Index int64 `json:"index" api:"required"` + Type constant.ContentBlockDelta `json:"type" api:"required"` // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. JSON struct { Delta respjson.Field @@ -5140,9 +5045,9 @@ func (r *BetaRawContentBlockDeltaEvent) UnmarshalJSON(data []byte) error { type BetaRawContentBlockStartEvent struct { // Response model for a file uploaded to the container. - ContentBlock BetaRawContentBlockStartEventContentBlockUnion `json:"content_block,required"` - Index int64 `json:"index,required"` - Type constant.ContentBlockStart `json:"type,required"` + ContentBlock BetaRawContentBlockStartEventContentBlockUnion `json:"content_block" api:"required"` + Index int64 `json:"index" api:"required"` + Type constant.ContentBlockStart `json:"type" api:"required"` // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. JSON struct { ContentBlock respjson.Field @@ -5555,8 +5460,8 @@ func (r *BetaRawContentBlockStartEventContentBlockUnionContentContent) Unmarshal } type BetaRawContentBlockStopEvent struct { - Index int64 `json:"index,required"` - Type constant.ContentBlockStop `json:"type,required"` + Index int64 `json:"index" api:"required"` + Type constant.ContentBlockStop `json:"type" api:"required"` // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. JSON struct { Index respjson.Field @@ -5574,9 +5479,9 @@ func (r *BetaRawContentBlockStopEvent) UnmarshalJSON(data []byte) error { type BetaRawMessageDeltaEvent struct { // Information about context management strategies applied during the request - ContextManagement BetaContextManagementResponse `json:"context_management,required"` - Delta BetaRawMessageDeltaEventDelta `json:"delta,required"` - Type constant.MessageDelta `json:"type,required"` + ContextManagement BetaContextManagementResponse `json:"context_management" api:"required"` + Delta BetaRawMessageDeltaEventDelta `json:"delta" api:"required"` + Type constant.MessageDelta `json:"type" api:"required"` // Billing and rate-limit usage. // // Anthropic's API bills and rate-limits by token counts, as tokens represent the @@ -5592,7 +5497,7 @@ type BetaRawMessageDeltaEvent struct { // // Total input tokens in a request is the summation of `input_tokens`, // `cache_creation_input_tokens`, and `cache_read_input_tokens`. - Usage BetaMessageDeltaUsage `json:"usage,required"` + Usage BetaMessageDeltaUsage `json:"usage" api:"required"` // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. JSON struct { ContextManagement respjson.Field @@ -5613,11 +5518,11 @@ func (r *BetaRawMessageDeltaEvent) UnmarshalJSON(data []byte) error { type BetaRawMessageDeltaEventDelta struct { // Information about the container used in the request (for the code execution // tool) - Container BetaContainer `json:"container,required"` + Container BetaContainer `json:"container" api:"required"` // Any of "end_turn", "max_tokens", "stop_sequence", "tool_use", "pause_turn", // "compaction", "refusal", "model_context_window_exceeded". - StopReason BetaStopReason `json:"stop_reason,required"` - StopSequence string `json:"stop_sequence,required"` + StopReason BetaStopReason `json:"stop_reason" api:"required"` + StopSequence string `json:"stop_sequence" api:"required"` // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. JSON struct { Container respjson.Field @@ -5635,8 +5540,8 @@ func (r *BetaRawMessageDeltaEventDelta) UnmarshalJSON(data []byte) error { } type BetaRawMessageStartEvent struct { - Message BetaMessage `json:"message,required"` - Type constant.MessageStart `json:"type,required"` + Message BetaMessage `json:"message" api:"required"` + Type constant.MessageStart `json:"type" api:"required"` // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. JSON struct { Message respjson.Field @@ -5653,7 +5558,7 @@ func (r *BetaRawMessageStartEvent) UnmarshalJSON(data []byte) error { } type BetaRawMessageStopEvent struct { - Type constant.MessageStop `json:"type,required"` + Type constant.MessageStop `json:"type" api:"required"` // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. JSON struct { Type respjson.Field @@ -5831,8 +5736,8 @@ func (r *BetaRawMessageStreamEventUnionDelta) UnmarshalJSON(data []byte) error { } type BetaRedactedThinkingBlock struct { - Data string `json:"data,required"` - Type constant.RedactedThinking `json:"type,required"` + Data string `json:"data" api:"required"` + Type constant.RedactedThinking `json:"type" api:"required"` // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. JSON struct { Data respjson.Field @@ -5850,10 +5755,10 @@ func (r *BetaRedactedThinkingBlock) UnmarshalJSON(data []byte) error { // The properties Data, Type are required. type BetaRedactedThinkingBlockParam struct { - Data string `json:"data,required"` + Data string `json:"data" api:"required"` // This field can be elided, and will marshal its zero value as // "redacted_thinking". - Type constant.RedactedThinking `json:"type,required"` + Type constant.RedactedThinking `json:"type" api:"required"` paramObj } @@ -5867,14 +5772,14 @@ func (r *BetaRedactedThinkingBlockParam) UnmarshalJSON(data []byte) error { // The properties Source, Type are required. type BetaRequestDocumentBlockParam struct { - Source BetaRequestDocumentBlockSourceUnionParam `json:"source,omitzero,required"` + Source BetaRequestDocumentBlockSourceUnionParam `json:"source,omitzero" api:"required"` Context param.Opt[string] `json:"context,omitzero"` Title param.Opt[string] `json:"title,omitzero"` // Create a cache control breakpoint at this content block. CacheControl BetaCacheControlEphemeralParam `json:"cache_control,omitzero"` Citations BetaCitationsConfigParam `json:"citations,omitzero"` // This field can be elided, and will marshal its zero value as "document". - Type constant.Document `json:"type,required"` + Type constant.Document `json:"type" api:"required"` paramObj } @@ -6000,12 +5905,12 @@ func (r *BetaRequestMCPServerToolConfigurationParam) UnmarshalJSON(data []byte) // The properties Name, Type, URL are required. type BetaRequestMCPServerURLDefinitionParam struct { - Name string `json:"name,required"` - URL string `json:"url,required"` + Name string `json:"name" api:"required"` + URL string `json:"url" api:"required"` AuthorizationToken param.Opt[string] `json:"authorization_token,omitzero"` ToolConfiguration BetaRequestMCPServerToolConfigurationParam `json:"tool_configuration,omitzero"` // This field can be elided, and will marshal its zero value as "url". - Type constant.URL `json:"type,required"` + Type constant.URL `json:"type" api:"required"` paramObj } @@ -6019,13 +5924,13 @@ func (r *BetaRequestMCPServerURLDefinitionParam) UnmarshalJSON(data []byte) erro // The properties ToolUseID, Type are required. type BetaRequestMCPToolResultBlockParam struct { - ToolUseID string `json:"tool_use_id,required"` + ToolUseID string `json:"tool_use_id" api:"required"` IsError param.Opt[bool] `json:"is_error,omitzero"` // Create a cache control breakpoint at this content block. CacheControl BetaCacheControlEphemeralParam `json:"cache_control,omitzero"` Content BetaRequestMCPToolResultBlockParamContentUnion `json:"content,omitzero"` // This field can be elided, and will marshal its zero value as "mcp_tool_result". - Type constant.MCPToolResult `json:"type,required"` + Type constant.MCPToolResult `json:"type" api:"required"` paramObj } @@ -6064,14 +5969,14 @@ func (u *BetaRequestMCPToolResultBlockParamContentUnion) asAny() any { // The properties Content, Source, Title, Type are required. type BetaSearchResultBlockParam struct { - Content []BetaTextBlockParam `json:"content,omitzero,required"` - Source string `json:"source,required"` - Title string `json:"title,required"` + Content []BetaTextBlockParam `json:"content,omitzero" api:"required"` + Source string `json:"source" api:"required"` + Title string `json:"title" api:"required"` // Create a cache control breakpoint at this content block. CacheControl BetaCacheControlEphemeralParam `json:"cache_control,omitzero"` Citations BetaCitationsConfigParam `json:"citations,omitzero"` // This field can be elided, and will marshal its zero value as "search_result". - Type constant.SearchResult `json:"type,required"` + Type constant.SearchResult `json:"type" api:"required"` paramObj } @@ -6085,8 +5990,8 @@ func (r *BetaSearchResultBlockParam) UnmarshalJSON(data []byte) error { // Tool invocation generated by a server-side tool. type BetaServerToolCaller struct { - ToolID string `json:"tool_id,required"` - Type constant.CodeExecution20250825 `json:"type,required"` + ToolID string `json:"tool_id" api:"required"` + Type constant.CodeExecution20250825 `json:"type" api:"required"` // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. JSON struct { ToolID respjson.Field @@ -6115,10 +6020,10 @@ func (r BetaServerToolCaller) ToParam() BetaServerToolCallerParam { // // The properties ToolID, Type are required. type BetaServerToolCallerParam struct { - ToolID string `json:"tool_id,required"` + ToolID string `json:"tool_id" api:"required"` // This field can be elided, and will marshal its zero value as // "code_execution_20250825". - Type constant.CodeExecution20250825 `json:"type,required"` + Type constant.CodeExecution20250825 `json:"type" api:"required"` paramObj } @@ -6131,8 +6036,8 @@ func (r *BetaServerToolCallerParam) UnmarshalJSON(data []byte) error { } type BetaServerToolCaller20260120 struct { - ToolID string `json:"tool_id,required"` - Type constant.CodeExecution20260120 `json:"type,required"` + ToolID string `json:"tool_id" api:"required"` + Type constant.CodeExecution20260120 `json:"type" api:"required"` // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. JSON struct { ToolID respjson.Field @@ -6160,10 +6065,10 @@ func (r BetaServerToolCaller20260120) ToParam() BetaServerToolCaller20260120Para // The properties ToolID, Type are required. type BetaServerToolCaller20260120Param struct { - ToolID string `json:"tool_id,required"` + ToolID string `json:"tool_id" api:"required"` // This field can be elided, and will marshal its zero value as // "code_execution_20260120". - Type constant.CodeExecution20260120 `json:"type,required"` + Type constant.CodeExecution20260120 `json:"type" api:"required"` paramObj } @@ -6177,9 +6082,9 @@ func (r *BetaServerToolCaller20260120Param) UnmarshalJSON(data []byte) error { type BetaServerToolUsage struct { // The number of web fetch tool requests. - WebFetchRequests int64 `json:"web_fetch_requests,required"` + WebFetchRequests int64 `json:"web_fetch_requests" api:"required"` // The number of web search tool requests. - WebSearchRequests int64 `json:"web_search_requests,required"` + WebSearchRequests int64 `json:"web_search_requests" api:"required"` // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. JSON struct { WebFetchRequests respjson.Field @@ -6196,12 +6101,12 @@ func (r *BetaServerToolUsage) UnmarshalJSON(data []byte) error { } type BetaServerToolUseBlock struct { - ID string `json:"id,required"` - Input any `json:"input,required"` + ID string `json:"id" api:"required"` + Input any `json:"input" api:"required"` // Any of "web_search", "web_fetch", "code_execution", "bash_code_execution", // "text_editor_code_execution", "tool_search_tool_regex", "tool_search_tool_bm25". - Name BetaServerToolUseBlockName `json:"name,required"` - Type constant.ServerToolUse `json:"type,required"` + Name BetaServerToolUseBlockName `json:"name" api:"required"` + Type constant.ServerToolUse `json:"type" api:"required"` // Tool invocation directly from the model. Caller BetaServerToolUseBlockCallerUnion `json:"caller"` // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. @@ -6308,17 +6213,17 @@ func (r *BetaServerToolUseBlockCallerUnion) UnmarshalJSON(data []byte) error { // The properties ID, Input, Name, Type are required. type BetaServerToolUseBlockParam struct { - ID string `json:"id,required"` - Input any `json:"input,omitzero,required"` + ID string `json:"id" api:"required"` + Input any `json:"input,omitzero" api:"required"` // Any of "web_search", "web_fetch", "code_execution", "bash_code_execution", // "text_editor_code_execution", "tool_search_tool_regex", "tool_search_tool_bm25". - Name BetaServerToolUseBlockParamName `json:"name,omitzero,required"` + Name BetaServerToolUseBlockParamName `json:"name,omitzero" api:"required"` // Create a cache control breakpoint at this content block. CacheControl BetaCacheControlEphemeralParam `json:"cache_control,omitzero"` // Tool invocation directly from the model. Caller BetaServerToolUseBlockParamCallerUnion `json:"caller,omitzero"` // This field can be elided, and will marshal its zero value as "server_tool_use". - Type constant.ServerToolUse `json:"type,required"` + Type constant.ServerToolUse `json:"type" api:"required"` paramObj } @@ -6392,18 +6297,9 @@ func (u BetaServerToolUseBlockParamCallerUnion) GetToolID() *string { return nil } -func init() { - apijson.RegisterUnion[BetaServerToolUseBlockParamCallerUnion]( - "type", - apijson.Discriminator[BetaDirectCallerParam]("direct"), - apijson.Discriminator[BetaServerToolCallerParam]("code_execution_20250825"), - apijson.Discriminator[BetaServerToolCaller20260120Param]("code_execution_20260120"), - ) -} - type BetaSignatureDelta struct { - Signature string `json:"signature,required"` - Type constant.SignatureDelta `json:"type,required"` + Signature string `json:"signature" api:"required"` + Type constant.SignatureDelta `json:"type" api:"required"` // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. JSON struct { Signature respjson.Field @@ -6422,13 +6318,13 @@ func (r *BetaSignatureDelta) UnmarshalJSON(data []byte) error { // A skill that was loaded in a container (response model). type BetaSkill struct { // Skill ID - SkillID string `json:"skill_id,required"` + SkillID string `json:"skill_id" api:"required"` // Type of skill - either 'anthropic' (built-in) or 'custom' (user-defined) // // Any of "anthropic", "custom". - Type BetaSkillType `json:"type,required"` + Type BetaSkillType `json:"type" api:"required"` // Skill version or 'latest' for most recent version - Version string `json:"version,required"` + Version string `json:"version" api:"required"` // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. JSON struct { SkillID respjson.Field @@ -6458,11 +6354,11 @@ const ( // The properties SkillID, Type are required. type BetaSkillParams struct { // Skill ID - SkillID string `json:"skill_id,required"` + SkillID string `json:"skill_id" api:"required"` // Type of skill - either 'anthropic' (built-in) or 'custom' (user-defined) // // Any of "anthropic", "custom". - Type BetaSkillParamsType `json:"type,omitzero,required"` + Type BetaSkillParamsType `json:"type,omitzero" api:"required"` // Skill version or 'latest' for most recent version Version param.Opt[string] `json:"version,omitzero"` paramObj @@ -6503,9 +6399,9 @@ type BetaTextBlock struct { // The type of citation returned will depend on the type of document being cited. // Citing a PDF results in `page_location`, plain text results in `char_location`, // and content document results in `content_block_location`. - Citations []BetaTextCitationUnion `json:"citations,required"` - Text string `json:"text,required"` - Type constant.Text `json:"type,required"` + Citations []BetaTextCitationUnion `json:"citations" api:"required"` + Text string `json:"text" api:"required"` + Type constant.Text `json:"type" api:"required"` // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. JSON struct { Citations respjson.Field @@ -6524,12 +6420,12 @@ func (r *BetaTextBlock) UnmarshalJSON(data []byte) error { // The properties Text, Type are required. type BetaTextBlockParam struct { - Text string `json:"text,required"` + Text string `json:"text" api:"required"` Citations []BetaTextCitationParamUnion `json:"citations,omitzero"` // Create a cache control breakpoint at this content block. CacheControl BetaCacheControlEphemeralParam `json:"cache_control,omitzero"` // This field can be elided, and will marshal its zero value as "text". - Type constant.Text `json:"type,required"` + Type constant.Text `json:"type" api:"required"` paramObj } @@ -6858,8 +6754,8 @@ func (u BetaTextCitationParamUnion) GetTitle() *string { } type BetaTextDelta struct { - Text string `json:"text,required"` - Type constant.TextDelta `json:"type,required"` + Text string `json:"text" api:"required"` + Type constant.TextDelta `json:"type" api:"required"` // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. JSON struct { Text respjson.Field @@ -6876,8 +6772,8 @@ func (r *BetaTextDelta) UnmarshalJSON(data []byte) error { } type BetaTextEditorCodeExecutionCreateResultBlock struct { - IsFileUpdate bool `json:"is_file_update,required"` - Type constant.TextEditorCodeExecutionCreateResult `json:"type,required"` + IsFileUpdate bool `json:"is_file_update" api:"required"` + Type constant.TextEditorCodeExecutionCreateResult `json:"type" api:"required"` // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. JSON struct { IsFileUpdate respjson.Field @@ -6895,10 +6791,10 @@ func (r *BetaTextEditorCodeExecutionCreateResultBlock) UnmarshalJSON(data []byte // The properties IsFileUpdate, Type are required. type BetaTextEditorCodeExecutionCreateResultBlockParam struct { - IsFileUpdate bool `json:"is_file_update,required"` + IsFileUpdate bool `json:"is_file_update" api:"required"` // This field can be elided, and will marshal its zero value as // "text_editor_code_execution_create_result". - Type constant.TextEditorCodeExecutionCreateResult `json:"type,required"` + Type constant.TextEditorCodeExecutionCreateResult `json:"type" api:"required"` paramObj } @@ -6911,12 +6807,12 @@ func (r *BetaTextEditorCodeExecutionCreateResultBlockParam) UnmarshalJSON(data [ } type BetaTextEditorCodeExecutionStrReplaceResultBlock struct { - Lines []string `json:"lines,required"` - NewLines int64 `json:"new_lines,required"` - NewStart int64 `json:"new_start,required"` - OldLines int64 `json:"old_lines,required"` - OldStart int64 `json:"old_start,required"` - Type constant.TextEditorCodeExecutionStrReplaceResult `json:"type,required"` + Lines []string `json:"lines" api:"required"` + NewLines int64 `json:"new_lines" api:"required"` + NewStart int64 `json:"new_start" api:"required"` + OldLines int64 `json:"old_lines" api:"required"` + OldStart int64 `json:"old_start" api:"required"` + Type constant.TextEditorCodeExecutionStrReplaceResult `json:"type" api:"required"` // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. JSON struct { Lines respjson.Field @@ -6945,7 +6841,7 @@ type BetaTextEditorCodeExecutionStrReplaceResultBlockParam struct { Lines []string `json:"lines,omitzero"` // This field can be elided, and will marshal its zero value as // "text_editor_code_execution_str_replace_result". - Type constant.TextEditorCodeExecutionStrReplaceResult `json:"type,required"` + Type constant.TextEditorCodeExecutionStrReplaceResult `json:"type" api:"required"` paramObj } @@ -6958,9 +6854,9 @@ func (r *BetaTextEditorCodeExecutionStrReplaceResultBlockParam) UnmarshalJSON(da } type BetaTextEditorCodeExecutionToolResultBlock struct { - Content BetaTextEditorCodeExecutionToolResultBlockContentUnion `json:"content,required"` - ToolUseID string `json:"tool_use_id,required"` - Type constant.TextEditorCodeExecutionToolResult `json:"type,required"` + Content BetaTextEditorCodeExecutionToolResultBlockContentUnion `json:"content" api:"required"` + ToolUseID string `json:"tool_use_id" api:"required"` + Type constant.TextEditorCodeExecutionToolResult `json:"type" api:"required"` // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. JSON struct { Content respjson.Field @@ -7060,13 +6956,13 @@ func (r *BetaTextEditorCodeExecutionToolResultBlockContentUnion) UnmarshalJSON(d // The properties Content, ToolUseID, Type are required. type BetaTextEditorCodeExecutionToolResultBlockParam struct { - Content BetaTextEditorCodeExecutionToolResultBlockParamContentUnion `json:"content,omitzero,required"` - ToolUseID string `json:"tool_use_id,required"` + Content BetaTextEditorCodeExecutionToolResultBlockParamContentUnion `json:"content,omitzero" api:"required"` + ToolUseID string `json:"tool_use_id" api:"required"` // Create a cache control breakpoint at this content block. CacheControl BetaCacheControlEphemeralParam `json:"cache_control,omitzero"` // This field can be elided, and will marshal its zero value as // "text_editor_code_execution_tool_result". - Type constant.TextEditorCodeExecutionToolResult `json:"type,required"` + Type constant.TextEditorCodeExecutionToolResult `json:"type" api:"required"` paramObj } @@ -7230,9 +7126,9 @@ func (u BetaTextEditorCodeExecutionToolResultBlockParamContentUnion) GetType() * type BetaTextEditorCodeExecutionToolResultError struct { // Any of "invalid_tool_input", "unavailable", "too_many_requests", // "execution_time_exceeded", "file_not_found". - ErrorCode BetaTextEditorCodeExecutionToolResultErrorErrorCode `json:"error_code,required"` - ErrorMessage string `json:"error_message,required"` - Type constant.TextEditorCodeExecutionToolResultError `json:"type,required"` + ErrorCode BetaTextEditorCodeExecutionToolResultErrorErrorCode `json:"error_code" api:"required"` + ErrorMessage string `json:"error_message" api:"required"` + Type constant.TextEditorCodeExecutionToolResultError `json:"type" api:"required"` // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. JSON struct { ErrorCode respjson.Field @@ -7263,11 +7159,11 @@ const ( type BetaTextEditorCodeExecutionToolResultErrorParam struct { // Any of "invalid_tool_input", "unavailable", "too_many_requests", // "execution_time_exceeded", "file_not_found". - ErrorCode BetaTextEditorCodeExecutionToolResultErrorParamErrorCode `json:"error_code,omitzero,required"` + ErrorCode BetaTextEditorCodeExecutionToolResultErrorParamErrorCode `json:"error_code,omitzero" api:"required"` ErrorMessage param.Opt[string] `json:"error_message,omitzero"` // This field can be elided, and will marshal its zero value as // "text_editor_code_execution_tool_result_error". - Type constant.TextEditorCodeExecutionToolResultError `json:"type,required"` + Type constant.TextEditorCodeExecutionToolResultError `json:"type" api:"required"` paramObj } @@ -7290,13 +7186,13 @@ const ( ) type BetaTextEditorCodeExecutionViewResultBlock struct { - Content string `json:"content,required"` + Content string `json:"content" api:"required"` // Any of "text", "image", "pdf". - FileType BetaTextEditorCodeExecutionViewResultBlockFileType `json:"file_type,required"` - NumLines int64 `json:"num_lines,required"` - StartLine int64 `json:"start_line,required"` - TotalLines int64 `json:"total_lines,required"` - Type constant.TextEditorCodeExecutionViewResult `json:"type,required"` + FileType BetaTextEditorCodeExecutionViewResultBlockFileType `json:"file_type" api:"required"` + NumLines int64 `json:"num_lines" api:"required"` + StartLine int64 `json:"start_line" api:"required"` + TotalLines int64 `json:"total_lines" api:"required"` + Type constant.TextEditorCodeExecutionViewResult `json:"type" api:"required"` // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. JSON struct { Content respjson.Field @@ -7326,15 +7222,15 @@ const ( // The properties Content, FileType, Type are required. type BetaTextEditorCodeExecutionViewResultBlockParam struct { - Content string `json:"content,required"` + Content string `json:"content" api:"required"` // Any of "text", "image", "pdf". - FileType BetaTextEditorCodeExecutionViewResultBlockParamFileType `json:"file_type,omitzero,required"` + FileType BetaTextEditorCodeExecutionViewResultBlockParamFileType `json:"file_type,omitzero" api:"required"` NumLines param.Opt[int64] `json:"num_lines,omitzero"` StartLine param.Opt[int64] `json:"start_line,omitzero"` TotalLines param.Opt[int64] `json:"total_lines,omitzero"` // This field can be elided, and will marshal its zero value as // "text_editor_code_execution_view_result". - Type constant.TextEditorCodeExecutionViewResult `json:"type,required"` + Type constant.TextEditorCodeExecutionViewResult `json:"type" api:"required"` paramObj } @@ -7355,9 +7251,9 @@ const ( ) type BetaThinkingBlock struct { - Signature string `json:"signature,required"` - Thinking string `json:"thinking,required"` - Type constant.Thinking `json:"type,required"` + Signature string `json:"signature" api:"required"` + Thinking string `json:"thinking" api:"required"` + Type constant.Thinking `json:"type" api:"required"` // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. JSON struct { Signature respjson.Field @@ -7376,10 +7272,10 @@ func (r *BetaThinkingBlock) UnmarshalJSON(data []byte) error { // The properties Signature, Thinking, Type are required. type BetaThinkingBlockParam struct { - Signature string `json:"signature,required"` - Thinking string `json:"thinking,required"` + Signature string `json:"signature" api:"required"` + Thinking string `json:"thinking" api:"required"` // This field can be elided, and will marshal its zero value as "thinking". - Type constant.Thinking `json:"type,required"` + Type constant.Thinking `json:"type" api:"required"` paramObj } @@ -7391,16 +7287,17 @@ func (r *BetaThinkingBlockParam) UnmarshalJSON(data []byte) error { return apijson.UnmarshalRoot(data, r) } -func NewBetaThinkingConfigAdaptiveParam() BetaThinkingConfigAdaptiveParam { - return BetaThinkingConfigAdaptiveParam{ - Type: "adaptive", - } -} - -// This struct has a constant value, construct it with -// [NewBetaThinkingConfigAdaptiveParam]. +// The property Type is required. type BetaThinkingConfigAdaptiveParam struct { - Type constant.Adaptive `json:"type,required"` + // Controls how thinking content appears in the response. When set to `summarized`, + // thinking is returned normally. When set to `omitted`, thinking content is + // redacted but a signature is returned for multi-turn continuity. Defaults to + // `summarized`. + // + // Any of "summarized", "omitted". + Display BetaThinkingConfigAdaptiveDisplay `json:"display,omitzero"` + // This field can be elided, and will marshal its zero value as "adaptive". + Type constant.Adaptive `json:"type" api:"required"` paramObj } @@ -7412,6 +7309,17 @@ func (r *BetaThinkingConfigAdaptiveParam) UnmarshalJSON(data []byte) error { return apijson.UnmarshalRoot(data, r) } +// Controls how thinking content appears in the response. When set to `summarized`, +// thinking is returned normally. When set to `omitted`, thinking content is +// redacted but a signature is returned for multi-turn continuity. Defaults to +// `summarized`. +type BetaThinkingConfigAdaptiveDisplay string + +const ( + BetaThinkingConfigAdaptiveDisplaySummarized BetaThinkingConfigAdaptiveDisplay = "summarized" + BetaThinkingConfigAdaptiveDisplayOmitted BetaThinkingConfigAdaptiveDisplay = "omitted" +) + func NewBetaThinkingConfigDisabledParam() BetaThinkingConfigDisabledParam { return BetaThinkingConfigDisabledParam{ Type: "disabled", @@ -7421,7 +7329,7 @@ func NewBetaThinkingConfigDisabledParam() BetaThinkingConfigDisabledParam { // This struct has a constant value, construct it with // [NewBetaThinkingConfigDisabledParam]. type BetaThinkingConfigDisabledParam struct { - Type constant.Disabled `json:"type,required"` + Type constant.Disabled `json:"type" api:"required"` paramObj } @@ -7444,9 +7352,16 @@ type BetaThinkingConfigEnabledParam struct { // See // [extended thinking](https://docs.claude.com/en/docs/build-with-claude/extended-thinking) // for details. - BudgetTokens int64 `json:"budget_tokens,required"` + BudgetTokens int64 `json:"budget_tokens" api:"required"` + // Controls how thinking content appears in the response. When set to `summarized`, + // thinking is returned normally. When set to `omitted`, thinking content is + // redacted but a signature is returned for multi-turn continuity. Defaults to + // `summarized`. + // + // Any of "summarized", "omitted". + Display BetaThinkingConfigEnabledDisplay `json:"display,omitzero"` // This field can be elided, and will marshal its zero value as "enabled". - Type constant.Enabled `json:"type,required"` + Type constant.Enabled `json:"type" api:"required"` paramObj } @@ -7458,6 +7373,17 @@ func (r *BetaThinkingConfigEnabledParam) UnmarshalJSON(data []byte) error { return apijson.UnmarshalRoot(data, r) } +// Controls how thinking content appears in the response. When set to `summarized`, +// thinking is returned normally. When set to `omitted`, thinking content is +// redacted but a signature is returned for multi-turn continuity. Defaults to +// `summarized`. +type BetaThinkingConfigEnabledDisplay string + +const ( + BetaThinkingConfigEnabledDisplaySummarized BetaThinkingConfigEnabledDisplay = "summarized" + BetaThinkingConfigEnabledDisplayOmitted BetaThinkingConfigEnabledDisplay = "omitted" +) + func BetaThinkingConfigParamOfEnabled(budgetTokens int64) BetaThinkingConfigParamUnion { var enabled BetaThinkingConfigEnabledParam enabled.BudgetTokens = budgetTokens @@ -7512,10 +7438,19 @@ func (u BetaThinkingConfigParamUnion) GetType() *string { return nil } +// Returns a pointer to the underlying variant's property, if present. +func (u BetaThinkingConfigParamUnion) GetDisplay() *string { + if vt := u.OfEnabled; vt != nil { + return (*string)(&vt.Display) + } else if vt := u.OfAdaptive; vt != nil { + return (*string)(&vt.Display) + } + return nil +} type BetaThinkingDelta struct { - Thinking string `json:"thinking,required"` - Type constant.ThinkingDelta `json:"type,required"` + Thinking string `json:"thinking" api:"required"` + Type constant.ThinkingDelta `json:"type" api:"required"` // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. JSON struct { Thinking respjson.Field @@ -7533,9 +7468,9 @@ func (r *BetaThinkingDelta) UnmarshalJSON(data []byte) error { // The properties Type, Value are required. type BetaThinkingTurnsParam struct { - Value int64 `json:"value,required"` + Value int64 `json:"value" api:"required"` // This field can be elided, and will marshal its zero value as "thinking_turns". - Type constant.ThinkingTurns `json:"type,required"` + Type constant.ThinkingTurns `json:"type" api:"required"` paramObj } @@ -7553,11 +7488,11 @@ type BetaToolParam struct { // // This defines the shape of the `input` that your tool accepts and that the model // will produce. - InputSchema BetaToolInputSchemaParam `json:"input_schema,omitzero,required"` + InputSchema BetaToolInputSchemaParam `json:"input_schema,omitzero" api:"required"` // Name of the tool. // // This is how the tool will be called by the model and in `tool_use` blocks. - Name string `json:"name,required"` + Name string `json:"name" api:"required"` // Enable eager input streaming for this tool. When true, tool input parameters // will be streamed incrementally as they are generated, and types will be inferred // on-the-fly rather than buffering the full JSON output. When false, streaming is @@ -7604,7 +7539,7 @@ type BetaToolInputSchemaParam struct { Properties any `json:"properties,omitzero"` Required []string `json:"required,omitzero"` // This field can be elided, and will marshal its zero value as "object". - Type constant.Object `json:"type,required"` + Type constant.Object `json:"type" api:"required"` ExtraFields map[string]any `json:"-"` paramObj } @@ -7640,9 +7575,9 @@ type BetaToolBash20241022Param struct { // This is how the tool will be called by the model and in `tool_use` blocks. // // This field can be elided, and will marshal its zero value as "bash". - Name constant.Bash `json:"name,required"` + Name constant.Bash `json:"name" api:"required"` // This field can be elided, and will marshal its zero value as "bash_20241022". - Type constant.Bash20241022 `json:"type,required"` + Type constant.Bash20241022 `json:"type" api:"required"` paramObj } @@ -7671,9 +7606,9 @@ type BetaToolBash20250124Param struct { // This is how the tool will be called by the model and in `tool_use` blocks. // // This field can be elided, and will marshal its zero value as "bash". - Name constant.Bash `json:"name,required"` + Name constant.Bash `json:"name" api:"required"` // This field can be elided, and will marshal its zero value as "bash_20250124". - Type constant.Bash20250124 `json:"type,required"` + Type constant.Bash20250124 `json:"type" api:"required"` paramObj } @@ -7766,7 +7701,7 @@ type BetaToolChoiceAnyParam struct { // use. DisableParallelToolUse param.Opt[bool] `json:"disable_parallel_tool_use,omitzero"` // This field can be elided, and will marshal its zero value as "any". - Type constant.Any `json:"type,required"` + Type constant.Any `json:"type" api:"required"` paramObj } @@ -7788,7 +7723,7 @@ type BetaToolChoiceAutoParam struct { // use. DisableParallelToolUse param.Opt[bool] `json:"disable_parallel_tool_use,omitzero"` // This field can be elided, and will marshal its zero value as "auto". - Type constant.Auto `json:"type,required"` + Type constant.Auto `json:"type" api:"required"` paramObj } @@ -7811,7 +7746,7 @@ func NewBetaToolChoiceNoneParam() BetaToolChoiceNoneParam { // This struct has a constant value, construct it with // [NewBetaToolChoiceNoneParam]. type BetaToolChoiceNoneParam struct { - Type constant.None `json:"type,required"` + Type constant.None `json:"type" api:"required"` paramObj } @@ -7828,14 +7763,14 @@ func (r *BetaToolChoiceNoneParam) UnmarshalJSON(data []byte) error { // The properties Name, Type are required. type BetaToolChoiceToolParam struct { // The name of the tool to use. - Name string `json:"name,required"` + Name string `json:"name" api:"required"` // Whether to disable parallel tool use. // // Defaults to `false`. If set to `true`, the model will output exactly one tool // use. DisableParallelToolUse param.Opt[bool] `json:"disable_parallel_tool_use,omitzero"` // This field can be elided, and will marshal its zero value as "tool". - Type constant.Tool `json:"type,required"` + Type constant.Tool `json:"type" api:"required"` paramObj } @@ -7850,9 +7785,9 @@ func (r *BetaToolChoiceToolParam) UnmarshalJSON(data []byte) error { // The properties DisplayHeightPx, DisplayWidthPx, Name, Type are required. type BetaToolComputerUse20241022Param struct { // The height of the display in pixels. - DisplayHeightPx int64 `json:"display_height_px,required"` + DisplayHeightPx int64 `json:"display_height_px" api:"required"` // The width of the display in pixels. - DisplayWidthPx int64 `json:"display_width_px,required"` + DisplayWidthPx int64 `json:"display_width_px" api:"required"` // The X11 display number (e.g. 0, 1) for the display. DisplayNumber param.Opt[int64] `json:"display_number,omitzero"` // If true, tool will not be included in initial system prompt. Only loaded when @@ -7870,10 +7805,10 @@ type BetaToolComputerUse20241022Param struct { // This is how the tool will be called by the model and in `tool_use` blocks. // // This field can be elided, and will marshal its zero value as "computer". - Name constant.Computer `json:"name,required"` + Name constant.Computer `json:"name" api:"required"` // This field can be elided, and will marshal its zero value as // "computer_20241022". - Type constant.Computer20241022 `json:"type,required"` + Type constant.Computer20241022 `json:"type" api:"required"` paramObj } @@ -7888,9 +7823,9 @@ func (r *BetaToolComputerUse20241022Param) UnmarshalJSON(data []byte) error { // The properties DisplayHeightPx, DisplayWidthPx, Name, Type are required. type BetaToolComputerUse20250124Param struct { // The height of the display in pixels. - DisplayHeightPx int64 `json:"display_height_px,required"` + DisplayHeightPx int64 `json:"display_height_px" api:"required"` // The width of the display in pixels. - DisplayWidthPx int64 `json:"display_width_px,required"` + DisplayWidthPx int64 `json:"display_width_px" api:"required"` // The X11 display number (e.g. 0, 1) for the display. DisplayNumber param.Opt[int64] `json:"display_number,omitzero"` // If true, tool will not be included in initial system prompt. Only loaded when @@ -7908,10 +7843,10 @@ type BetaToolComputerUse20250124Param struct { // This is how the tool will be called by the model and in `tool_use` blocks. // // This field can be elided, and will marshal its zero value as "computer". - Name constant.Computer `json:"name,required"` + Name constant.Computer `json:"name" api:"required"` // This field can be elided, and will marshal its zero value as // "computer_20250124". - Type constant.Computer20250124 `json:"type,required"` + Type constant.Computer20250124 `json:"type" api:"required"` paramObj } @@ -7926,9 +7861,9 @@ func (r *BetaToolComputerUse20250124Param) UnmarshalJSON(data []byte) error { // The properties DisplayHeightPx, DisplayWidthPx, Name, Type are required. type BetaToolComputerUse20251124Param struct { // The height of the display in pixels. - DisplayHeightPx int64 `json:"display_height_px,required"` + DisplayHeightPx int64 `json:"display_height_px" api:"required"` // The width of the display in pixels. - DisplayWidthPx int64 `json:"display_width_px,required"` + DisplayWidthPx int64 `json:"display_width_px" api:"required"` // The X11 display number (e.g. 0, 1) for the display. DisplayNumber param.Opt[int64] `json:"display_number,omitzero"` // If true, tool will not be included in initial system prompt. Only loaded when @@ -7948,10 +7883,10 @@ type BetaToolComputerUse20251124Param struct { // This is how the tool will be called by the model and in `tool_use` blocks. // // This field can be elided, and will marshal its zero value as "computer". - Name constant.Computer `json:"name,required"` + Name constant.Computer `json:"name" api:"required"` // This field can be elided, and will marshal its zero value as // "computer_20251124". - Type constant.Computer20251124 `json:"type,required"` + Type constant.Computer20251124 `json:"type" api:"required"` paramObj } @@ -7964,8 +7899,8 @@ func (r *BetaToolComputerUse20251124Param) UnmarshalJSON(data []byte) error { } type BetaToolReferenceBlock struct { - ToolName string `json:"tool_name,required"` - Type constant.ToolReference `json:"type,required"` + ToolName string `json:"tool_name" api:"required"` + Type constant.ToolReference `json:"type" api:"required"` // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. JSON struct { ToolName respjson.Field @@ -7985,11 +7920,11 @@ func (r *BetaToolReferenceBlock) UnmarshalJSON(data []byte) error { // // The properties ToolName, Type are required. type BetaToolReferenceBlockParam struct { - ToolName string `json:"tool_name,required"` + ToolName string `json:"tool_name" api:"required"` // Create a cache control breakpoint at this content block. CacheControl BetaCacheControlEphemeralParam `json:"cache_control,omitzero"` // This field can be elided, and will marshal its zero value as "tool_reference". - Type constant.ToolReference `json:"type,required"` + Type constant.ToolReference `json:"type" api:"required"` paramObj } @@ -8003,13 +7938,13 @@ func (r *BetaToolReferenceBlockParam) UnmarshalJSON(data []byte) error { // The properties ToolUseID, Type are required. type BetaToolResultBlockParam struct { - ToolUseID string `json:"tool_use_id,required"` + ToolUseID string `json:"tool_use_id" api:"required"` IsError param.Opt[bool] `json:"is_error,omitzero"` // Create a cache control breakpoint at this content block. CacheControl BetaCacheControlEphemeralParam `json:"cache_control,omitzero"` Content []BetaToolResultBlockParamContentUnion `json:"content,omitzero"` // This field can be elided, and will marshal its zero value as "tool_result". - Type constant.ToolResult `json:"type,required"` + Type constant.ToolResult `json:"type" api:"required"` paramObj } @@ -8285,7 +8220,7 @@ func (u betaToolResultBlockParamContentUnionSource) GetFileID() *string { // The properties Name, Type are required. type BetaToolSearchToolBm25_20251119Param struct { // Any of "tool_search_tool_bm25_20251119", "tool_search_tool_bm25". - Type BetaToolSearchToolBm25_20251119Type `json:"type,omitzero,required"` + Type BetaToolSearchToolBm25_20251119Type `json:"type,omitzero" api:"required"` // If true, tool will not be included in initial system prompt. Only loaded when // returned via tool_reference from tool search. DeferLoading param.Opt[bool] `json:"defer_loading,omitzero"` @@ -8302,7 +8237,7 @@ type BetaToolSearchToolBm25_20251119Param struct { // // This field can be elided, and will marshal its zero value as // "tool_search_tool_bm25". - Name constant.ToolSearchToolBm25 `json:"name,required"` + Name constant.ToolSearchToolBm25 `json:"name" api:"required"` paramObj } @@ -8324,7 +8259,7 @@ const ( // The properties Name, Type are required. type BetaToolSearchToolRegex20251119Param struct { // Any of "tool_search_tool_regex_20251119", "tool_search_tool_regex". - Type BetaToolSearchToolRegex20251119Type `json:"type,omitzero,required"` + Type BetaToolSearchToolRegex20251119Type `json:"type,omitzero" api:"required"` // If true, tool will not be included in initial system prompt. Only loaded when // returned via tool_reference from tool search. DeferLoading param.Opt[bool] `json:"defer_loading,omitzero"` @@ -8340,7 +8275,7 @@ type BetaToolSearchToolRegex20251119Param struct { // // This field can be elided, and will marshal its zero value as // "tool_search_tool_regex". - Name constant.ToolSearchToolRegex `json:"name,required"` + Name constant.ToolSearchToolRegex `json:"name" api:"required"` paramObj } @@ -8360,9 +8295,9 @@ const ( ) type BetaToolSearchToolResultBlock struct { - Content BetaToolSearchToolResultBlockContentUnion `json:"content,required"` - ToolUseID string `json:"tool_use_id,required"` - Type constant.ToolSearchToolResult `json:"type,required"` + Content BetaToolSearchToolResultBlockContentUnion `json:"content" api:"required"` + ToolUseID string `json:"tool_use_id" api:"required"` + Type constant.ToolSearchToolResult `json:"type" api:"required"` // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. JSON struct { Content respjson.Field @@ -8420,13 +8355,13 @@ func (r *BetaToolSearchToolResultBlockContentUnion) UnmarshalJSON(data []byte) e // The properties Content, ToolUseID, Type are required. type BetaToolSearchToolResultBlockParam struct { - Content BetaToolSearchToolResultBlockParamContentUnion `json:"content,omitzero,required"` - ToolUseID string `json:"tool_use_id,required"` + Content BetaToolSearchToolResultBlockParamContentUnion `json:"content,omitzero" api:"required"` + ToolUseID string `json:"tool_use_id" api:"required"` // Create a cache control breakpoint at this content block. CacheControl BetaCacheControlEphemeralParam `json:"cache_control,omitzero"` // This field can be elided, and will marshal its zero value as // "tool_search_tool_result". - Type constant.ToolSearchToolResult `json:"type,required"` + Type constant.ToolSearchToolResult `json:"type" api:"required"` paramObj } @@ -8492,9 +8427,9 @@ func (u BetaToolSearchToolResultBlockParamContentUnion) GetType() *string { type BetaToolSearchToolResultError struct { // Any of "invalid_tool_input", "unavailable", "too_many_requests", // "execution_time_exceeded". - ErrorCode BetaToolSearchToolResultErrorErrorCode `json:"error_code,required"` - ErrorMessage string `json:"error_message,required"` - Type constant.ToolSearchToolResultError `json:"type,required"` + ErrorCode BetaToolSearchToolResultErrorErrorCode `json:"error_code" api:"required"` + ErrorMessage string `json:"error_message" api:"required"` + Type constant.ToolSearchToolResultError `json:"type" api:"required"` // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. JSON struct { ErrorCode respjson.Field @@ -8524,10 +8459,10 @@ const ( type BetaToolSearchToolResultErrorParam struct { // Any of "invalid_tool_input", "unavailable", "too_many_requests", // "execution_time_exceeded". - ErrorCode BetaToolSearchToolResultErrorParamErrorCode `json:"error_code,omitzero,required"` + ErrorCode BetaToolSearchToolResultErrorParamErrorCode `json:"error_code,omitzero" api:"required"` // This field can be elided, and will marshal its zero value as // "tool_search_tool_result_error". - Type constant.ToolSearchToolResultError `json:"type,required"` + Type constant.ToolSearchToolResultError `json:"type" api:"required"` paramObj } @@ -8549,8 +8484,8 @@ const ( ) type BetaToolSearchToolSearchResultBlock struct { - ToolReferences []BetaToolReferenceBlock `json:"tool_references,required"` - Type constant.ToolSearchToolSearchResult `json:"type,required"` + ToolReferences []BetaToolReferenceBlock `json:"tool_references" api:"required"` + Type constant.ToolSearchToolSearchResult `json:"type" api:"required"` // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. JSON struct { ToolReferences respjson.Field @@ -8568,10 +8503,10 @@ func (r *BetaToolSearchToolSearchResultBlock) UnmarshalJSON(data []byte) error { // The properties ToolReferences, Type are required. type BetaToolSearchToolSearchResultBlockParam struct { - ToolReferences []BetaToolReferenceBlockParam `json:"tool_references,omitzero,required"` + ToolReferences []BetaToolReferenceBlockParam `json:"tool_references,omitzero" api:"required"` // This field can be elided, and will marshal its zero value as // "tool_search_tool_search_result". - Type constant.ToolSearchToolSearchResult `json:"type,required"` + Type constant.ToolSearchToolSearchResult `json:"type" api:"required"` paramObj } @@ -8601,10 +8536,10 @@ type BetaToolTextEditor20241022Param struct { // // This field can be elided, and will marshal its zero value as // "str_replace_editor". - Name constant.StrReplaceEditor `json:"name,required"` + Name constant.StrReplaceEditor `json:"name" api:"required"` // This field can be elided, and will marshal its zero value as // "text_editor_20241022". - Type constant.TextEditor20241022 `json:"type,required"` + Type constant.TextEditor20241022 `json:"type" api:"required"` paramObj } @@ -8634,10 +8569,10 @@ type BetaToolTextEditor20250124Param struct { // // This field can be elided, and will marshal its zero value as // "str_replace_editor". - Name constant.StrReplaceEditor `json:"name,required"` + Name constant.StrReplaceEditor `json:"name" api:"required"` // This field can be elided, and will marshal its zero value as // "text_editor_20250124". - Type constant.TextEditor20250124 `json:"type,required"` + Type constant.TextEditor20250124 `json:"type" api:"required"` paramObj } @@ -8667,10 +8602,10 @@ type BetaToolTextEditor20250429Param struct { // // This field can be elided, and will marshal its zero value as // "str_replace_based_edit_tool". - Name constant.StrReplaceBasedEditTool `json:"name,required"` + Name constant.StrReplaceBasedEditTool `json:"name" api:"required"` // This field can be elided, and will marshal its zero value as // "text_editor_20250429". - Type constant.TextEditor20250429 `json:"type,required"` + Type constant.TextEditor20250429 `json:"type" api:"required"` paramObj } @@ -8703,10 +8638,10 @@ type BetaToolTextEditor20250728Param struct { // // This field can be elided, and will marshal its zero value as // "str_replace_based_edit_tool". - Name constant.StrReplaceBasedEditTool `json:"name,required"` + Name constant.StrReplaceBasedEditTool `json:"name" api:"required"` // This field can be elided, and will marshal its zero value as // "text_editor_20250728". - Type constant.TextEditor20250728 `json:"type,required"` + Type constant.TextEditor20250728 `json:"type" api:"required"` paramObj } @@ -8786,6 +8721,7 @@ type BetaToolUnionParam struct { OfWebFetchTool20250910 *BetaWebFetchTool20250910Param `json:",omitzero,inline"` OfWebSearchTool20260209 *BetaWebSearchTool20260209Param `json:",omitzero,inline"` OfWebFetchTool20260209 *BetaWebFetchTool20260209Param `json:",omitzero,inline"` + OfWebFetchTool20260309 *BetaWebFetchTool20260309Param `json:",omitzero,inline"` OfToolSearchToolBm25_20251119 *BetaToolSearchToolBm25_20251119Param `json:",omitzero,inline"` OfToolSearchToolRegex20251119 *BetaToolSearchToolRegex20251119Param `json:",omitzero,inline"` OfMCPToolset *BetaMCPToolsetParam `json:",omitzero,inline"` @@ -8811,6 +8747,7 @@ func (u BetaToolUnionParam) MarshalJSON() ([]byte, error) { u.OfWebFetchTool20250910, u.OfWebSearchTool20260209, u.OfWebFetchTool20260209, + u.OfWebFetchTool20260309, u.OfToolSearchToolBm25_20251119, u.OfToolSearchToolRegex20251119, u.OfMCPToolset) @@ -8856,6 +8793,8 @@ func (u *BetaToolUnionParam) asAny() any { return u.OfWebSearchTool20260209 } else if !param.IsOmitted(u.OfWebFetchTool20260209) { return u.OfWebFetchTool20260209 + } else if !param.IsOmitted(u.OfWebFetchTool20260309) { + return u.OfWebFetchTool20260309 } else if !param.IsOmitted(u.OfToolSearchToolBm25_20251119) { return u.OfToolSearchToolBm25_20251119 } else if !param.IsOmitted(u.OfToolSearchToolRegex20251119) { @@ -8906,6 +8845,14 @@ func (u BetaToolUnionParam) GetMaxCharacters() *int64 { return nil } +// Returns a pointer to the underlying variant's property, if present. +func (u BetaToolUnionParam) GetUseCache() *bool { + if vt := u.OfWebFetchTool20260309; vt != nil && vt.UseCache.Valid() { + return &vt.UseCache.Value + } + return nil +} + // Returns a pointer to the underlying variant's property, if present. func (u BetaToolUnionParam) GetMCPServerName() *string { if vt := u.OfMCPToolset; vt != nil { @@ -8968,6 +8915,8 @@ func (u BetaToolUnionParam) GetName() *string { return (*string)(&vt.Name) } else if vt := u.OfWebFetchTool20260209; vt != nil { return (*string)(&vt.Name) + } else if vt := u.OfWebFetchTool20260309; vt != nil { + return (*string)(&vt.Name) } else if vt := u.OfToolSearchToolBm25_20251119; vt != nil { return (*string)(&vt.Name) } else if vt := u.OfToolSearchToolRegex20251119; vt != nil { @@ -9014,6 +8963,8 @@ func (u BetaToolUnionParam) GetDeferLoading() *bool { return &vt.DeferLoading.Value } else if vt := u.OfWebFetchTool20260209; vt != nil && vt.DeferLoading.Valid() { return &vt.DeferLoading.Value + } else if vt := u.OfWebFetchTool20260309; vt != nil && vt.DeferLoading.Valid() { + return &vt.DeferLoading.Value } else if vt := u.OfToolSearchToolBm25_20251119; vt != nil && vt.DeferLoading.Valid() { return &vt.DeferLoading.Value } else if vt := u.OfToolSearchToolRegex20251119; vt != nil && vt.DeferLoading.Valid() { @@ -9060,6 +9011,8 @@ func (u BetaToolUnionParam) GetStrict() *bool { return &vt.Strict.Value } else if vt := u.OfWebFetchTool20260209; vt != nil && vt.Strict.Valid() { return &vt.Strict.Value + } else if vt := u.OfWebFetchTool20260309; vt != nil && vt.Strict.Valid() { + return &vt.Strict.Value } else if vt := u.OfToolSearchToolBm25_20251119; vt != nil && vt.Strict.Valid() { return &vt.Strict.Value } else if vt := u.OfToolSearchToolRegex20251119; vt != nil && vt.Strict.Valid() { @@ -9106,6 +9059,8 @@ func (u BetaToolUnionParam) GetType() *string { return (*string)(&vt.Type) } else if vt := u.OfWebFetchTool20260209; vt != nil { return (*string)(&vt.Type) + } else if vt := u.OfWebFetchTool20260309; vt != nil { + return (*string)(&vt.Type) } else if vt := u.OfToolSearchToolBm25_20251119; vt != nil { return (*string)(&vt.Type) } else if vt := u.OfToolSearchToolRegex20251119; vt != nil { @@ -9162,6 +9117,8 @@ func (u BetaToolUnionParam) GetMaxUses() *int64 { return &vt.MaxUses.Value } else if vt := u.OfWebFetchTool20260209; vt != nil && vt.MaxUses.Valid() { return &vt.MaxUses.Value + } else if vt := u.OfWebFetchTool20260309; vt != nil && vt.MaxUses.Valid() { + return &vt.MaxUses.Value } return nil } @@ -9172,6 +9129,8 @@ func (u BetaToolUnionParam) GetMaxContentTokens() *int64 { return &vt.MaxContentTokens.Value } else if vt := u.OfWebFetchTool20260209; vt != nil && vt.MaxContentTokens.Valid() { return &vt.MaxContentTokens.Value + } else if vt := u.OfWebFetchTool20260309; vt != nil && vt.MaxContentTokens.Valid() { + return &vt.MaxContentTokens.Value } return nil } @@ -9215,6 +9174,8 @@ func (u BetaToolUnionParam) GetAllowedCallers() []string { return vt.AllowedCallers } else if vt := u.OfWebFetchTool20260209; vt != nil { return vt.AllowedCallers + } else if vt := u.OfWebFetchTool20260309; vt != nil { + return vt.AllowedCallers } else if vt := u.OfToolSearchToolBm25_20251119; vt != nil { return vt.AllowedCallers } else if vt := u.OfToolSearchToolRegex20251119; vt != nil { @@ -9261,6 +9222,8 @@ func (u BetaToolUnionParam) GetCacheControl() *BetaCacheControlEphemeralParam { return &vt.CacheControl } else if vt := u.OfWebFetchTool20260209; vt != nil { return &vt.CacheControl + } else if vt := u.OfWebFetchTool20260309; vt != nil { + return &vt.CacheControl } else if vt := u.OfToolSearchToolBm25_20251119; vt != nil { return &vt.CacheControl } else if vt := u.OfToolSearchToolRegex20251119; vt != nil { @@ -9311,6 +9274,8 @@ func (u BetaToolUnionParam) GetAllowedDomains() []string { return vt.AllowedDomains } else if vt := u.OfWebFetchTool20260209; vt != nil { return vt.AllowedDomains + } else if vt := u.OfWebFetchTool20260309; vt != nil { + return vt.AllowedDomains } return nil } @@ -9326,6 +9291,8 @@ func (u BetaToolUnionParam) GetBlockedDomains() []string { return vt.BlockedDomains } else if vt := u.OfWebFetchTool20260209; vt != nil { return vt.BlockedDomains + } else if vt := u.OfWebFetchTool20260309; vt != nil { + return vt.BlockedDomains } return nil } @@ -9346,15 +9313,17 @@ func (u BetaToolUnionParam) GetCitations() *BetaCitationsConfigParam { return &vt.Citations } else if vt := u.OfWebFetchTool20260209; vt != nil { return &vt.Citations + } else if vt := u.OfWebFetchTool20260309; vt != nil { + return &vt.Citations } return nil } type BetaToolUseBlock struct { - ID string `json:"id,required"` - Input any `json:"input,required"` - Name string `json:"name,required"` - Type constant.ToolUse `json:"type,required"` + ID string `json:"id" api:"required"` + Input any `json:"input" api:"required"` + Name string `json:"name" api:"required"` + Type constant.ToolUse `json:"type" api:"required"` // Tool invocation directly from the model. Caller BetaToolUseBlockCallerUnion `json:"caller"` // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. @@ -9448,15 +9417,15 @@ func (r *BetaToolUseBlockCallerUnion) UnmarshalJSON(data []byte) error { // The properties ID, Input, Name, Type are required. type BetaToolUseBlockParam struct { - ID string `json:"id,required"` - Input any `json:"input,omitzero,required"` - Name string `json:"name,required"` + ID string `json:"id" api:"required"` + Input any `json:"input,omitzero" api:"required"` + Name string `json:"name" api:"required"` // Create a cache control breakpoint at this content block. CacheControl BetaCacheControlEphemeralParam `json:"cache_control,omitzero"` // Tool invocation directly from the model. Caller BetaToolUseBlockParamCallerUnion `json:"caller,omitzero"` // This field can be elided, and will marshal its zero value as "tool_use". - Type constant.ToolUse `json:"type,required"` + Type constant.ToolUse `json:"type" api:"required"` paramObj } @@ -9518,20 +9487,11 @@ func (u BetaToolUseBlockParamCallerUnion) GetToolID() *string { return nil } -func init() { - apijson.RegisterUnion[BetaToolUseBlockParamCallerUnion]( - "type", - apijson.Discriminator[BetaDirectCallerParam]("direct"), - apijson.Discriminator[BetaServerToolCallerParam]("code_execution_20250825"), - apijson.Discriminator[BetaServerToolCaller20260120Param]("code_execution_20260120"), - ) -} - // The properties Type, Value are required. type BetaToolUsesKeepParam struct { - Value int64 `json:"value,required"` + Value int64 `json:"value" api:"required"` // This field can be elided, and will marshal its zero value as "tool_uses". - Type constant.ToolUses `json:"type,required"` + Type constant.ToolUses `json:"type" api:"required"` paramObj } @@ -9545,9 +9505,9 @@ func (r *BetaToolUsesKeepParam) UnmarshalJSON(data []byte) error { // The properties Type, Value are required. type BetaToolUsesTriggerParam struct { - Value int64 `json:"value,required"` + Value int64 `json:"value" api:"required"` // This field can be elided, and will marshal its zero value as "tool_uses". - Type constant.ToolUses `json:"type,required"` + Type constant.ToolUses `json:"type" api:"required"` paramObj } @@ -9561,9 +9521,9 @@ func (r *BetaToolUsesTriggerParam) UnmarshalJSON(data []byte) error { // The properties Type, URL are required. type BetaURLImageSourceParam struct { - URL string `json:"url,required"` + URL string `json:"url" api:"required"` // This field can be elided, and will marshal its zero value as "url". - Type constant.URL `json:"type,required"` + Type constant.URL `json:"type" api:"required"` paramObj } @@ -9577,9 +9537,9 @@ func (r *BetaURLImageSourceParam) UnmarshalJSON(data []byte) error { // The properties Type, URL are required. type BetaURLPDFSourceParam struct { - URL string `json:"url,required"` + URL string `json:"url" api:"required"` // This field can be elided, and will marshal its zero value as "url". - Type constant.URL `json:"type,required"` + Type constant.URL `json:"type" api:"required"` paramObj } @@ -9593,15 +9553,15 @@ func (r *BetaURLPDFSourceParam) UnmarshalJSON(data []byte) error { type BetaUsage struct { // Breakdown of cached tokens by TTL - CacheCreation BetaCacheCreation `json:"cache_creation,required"` + CacheCreation BetaCacheCreation `json:"cache_creation" api:"required"` // The number of input tokens used to create the cache entry. - CacheCreationInputTokens int64 `json:"cache_creation_input_tokens,required"` + CacheCreationInputTokens int64 `json:"cache_creation_input_tokens" api:"required"` // The number of input tokens read from the cache. - CacheReadInputTokens int64 `json:"cache_read_input_tokens,required"` + CacheReadInputTokens int64 `json:"cache_read_input_tokens" api:"required"` // The geographic region where inference was performed for this request. - InferenceGeo string `json:"inference_geo,required"` + InferenceGeo string `json:"inference_geo" api:"required"` // The number of input tokens which were used. - InputTokens int64 `json:"input_tokens,required"` + InputTokens int64 `json:"input_tokens" api:"required"` // Per-iteration token usage breakdown. // // Each entry represents one sampling iteration, with its own input/output token @@ -9610,19 +9570,19 @@ type BetaUsage struct { // - Determine which iterations exceeded long context thresholds (>=200k tokens) // - Calculate the true context window size from the last iteration // - Understand token accumulation across server-side tool use loops - Iterations BetaIterationsUsage `json:"iterations,required"` + Iterations BetaIterationsUsage `json:"iterations" api:"required"` // The number of output tokens which were used. - OutputTokens int64 `json:"output_tokens,required"` + OutputTokens int64 `json:"output_tokens" api:"required"` // The number of server tool requests. - ServerToolUse BetaServerToolUsage `json:"server_tool_use,required"` + ServerToolUse BetaServerToolUsage `json:"server_tool_use" api:"required"` // If the request used the priority, standard, or batch tier. // // Any of "standard", "priority", "batch". - ServiceTier BetaUsageServiceTier `json:"service_tier,required"` + ServiceTier BetaUsageServiceTier `json:"service_tier" api:"required"` // The inference speed mode used for this request. // // Any of "standard", "fast". - Speed BetaUsageSpeed `json:"speed,required"` + Speed BetaUsageSpeed `json:"speed" api:"required"` // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. JSON struct { CacheCreation respjson.Field @@ -9676,7 +9636,7 @@ type BetaUserLocationParam struct { // The [IANA timezone](https://nodatime.org/TimeZones) of the user. Timezone param.Opt[string] `json:"timezone,omitzero"` // This field can be elided, and will marshal its zero value as "approximate". - Type constant.Approximate `json:"type,required"` + Type constant.Approximate `json:"type" api:"required"` paramObj } @@ -9689,12 +9649,12 @@ func (r *BetaUserLocationParam) UnmarshalJSON(data []byte) error { } type BetaWebFetchBlock struct { - Content BetaDocumentBlock `json:"content,required"` + Content BetaDocumentBlock `json:"content" api:"required"` // ISO 8601 timestamp when the content was retrieved - RetrievedAt string `json:"retrieved_at,required"` - Type constant.WebFetchResult `json:"type,required"` + RetrievedAt string `json:"retrieved_at" api:"required"` + Type constant.WebFetchResult `json:"type" api:"required"` // Fetched content URL - URL string `json:"url,required"` + URL string `json:"url" api:"required"` // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. JSON struct { Content respjson.Field @@ -9714,13 +9674,13 @@ func (r *BetaWebFetchBlock) UnmarshalJSON(data []byte) error { // The properties Content, Type, URL are required. type BetaWebFetchBlockParam struct { - Content BetaRequestDocumentBlockParam `json:"content,omitzero,required"` + Content BetaRequestDocumentBlockParam `json:"content,omitzero" api:"required"` // Fetched content URL - URL string `json:"url,required"` + URL string `json:"url" api:"required"` // ISO 8601 timestamp when the content was retrieved RetrievedAt param.Opt[string] `json:"retrieved_at,omitzero"` // This field can be elided, and will marshal its zero value as "web_fetch_result". - Type constant.WebFetchResult `json:"type,required"` + Type constant.WebFetchResult `json:"type" api:"required"` paramObj } @@ -9760,10 +9720,10 @@ type BetaWebFetchTool20250910Param struct { // This is how the tool will be called by the model and in `tool_use` blocks. // // This field can be elided, and will marshal its zero value as "web_fetch". - Name constant.WebFetch `json:"name,required"` + Name constant.WebFetch `json:"name" api:"required"` // This field can be elided, and will marshal its zero value as // "web_fetch_20250910". - Type constant.WebFetch20250910 `json:"type,required"` + Type constant.WebFetch20250910 `json:"type" api:"required"` paramObj } @@ -9803,10 +9763,10 @@ type BetaWebFetchTool20260209Param struct { // This is how the tool will be called by the model and in `tool_use` blocks. // // This field can be elided, and will marshal its zero value as "web_fetch". - Name constant.WebFetch `json:"name,required"` + Name constant.WebFetch `json:"name" api:"required"` // This field can be elided, and will marshal its zero value as // "web_fetch_20260209". - Type constant.WebFetch20260209 `json:"type,required"` + Type constant.WebFetch20260209 `json:"type" api:"required"` paramObj } @@ -9818,10 +9778,59 @@ func (r *BetaWebFetchTool20260209Param) UnmarshalJSON(data []byte) error { return apijson.UnmarshalRoot(data, r) } +// Web fetch tool with use_cache parameter for bypassing cached content. +// +// The properties Name, Type are required. +type BetaWebFetchTool20260309Param struct { + // Maximum number of tokens used by including web page text content in the context. + // The limit is approximate and does not apply to binary content such as PDFs. + MaxContentTokens param.Opt[int64] `json:"max_content_tokens,omitzero"` + // Maximum number of times the tool can be used in the API request. + MaxUses param.Opt[int64] `json:"max_uses,omitzero"` + // If true, tool will not be included in initial system prompt. Only loaded when + // returned via tool_reference from tool search. + DeferLoading param.Opt[bool] `json:"defer_loading,omitzero"` + // When true, guarantees schema validation on tool names and inputs + Strict param.Opt[bool] `json:"strict,omitzero"` + // Whether to use cached content. Set to false to bypass the cache and fetch fresh + // content. Only set to false when the user explicitly requests fresh content or + // when fetching rapidly-changing sources. + UseCache param.Opt[bool] `json:"use_cache,omitzero"` + // List of domains to allow fetching from + AllowedDomains []string `json:"allowed_domains,omitzero"` + // List of domains to block fetching from + BlockedDomains []string `json:"blocked_domains,omitzero"` + // Any of "direct", "code_execution_20250825", "code_execution_20260120". + AllowedCallers []string `json:"allowed_callers,omitzero"` + // Create a cache control breakpoint at this content block. + CacheControl BetaCacheControlEphemeralParam `json:"cache_control,omitzero"` + // Citations configuration for fetched documents. Citations are disabled by + // default. + Citations BetaCitationsConfigParam `json:"citations,omitzero"` + // Name of the tool. + // + // This is how the tool will be called by the model and in `tool_use` blocks. + // + // This field can be elided, and will marshal its zero value as "web_fetch". + Name constant.WebFetch `json:"name" api:"required"` + // This field can be elided, and will marshal its zero value as + // "web_fetch_20260309". + Type constant.WebFetch20260309 `json:"type" api:"required"` + paramObj +} + +func (r BetaWebFetchTool20260309Param) MarshalJSON() (data []byte, err error) { + type shadow BetaWebFetchTool20260309Param + return param.MarshalObject(r, (*shadow)(&r)) +} +func (r *BetaWebFetchTool20260309Param) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + type BetaWebFetchToolResultBlock struct { - Content BetaWebFetchToolResultBlockContentUnion `json:"content,required"` - ToolUseID string `json:"tool_use_id,required"` - Type constant.WebFetchToolResult `json:"type,required"` + Content BetaWebFetchToolResultBlockContentUnion `json:"content" api:"required"` + ToolUseID string `json:"tool_use_id" api:"required"` + Type constant.WebFetchToolResult `json:"type" api:"required"` // Tool invocation directly from the model. Caller BetaWebFetchToolResultBlockCallerUnion `json:"caller"` // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. @@ -9957,15 +9966,15 @@ func (r *BetaWebFetchToolResultBlockCallerUnion) UnmarshalJSON(data []byte) erro // The properties Content, ToolUseID, Type are required. type BetaWebFetchToolResultBlockParam struct { - Content BetaWebFetchToolResultBlockParamContentUnion `json:"content,omitzero,required"` - ToolUseID string `json:"tool_use_id,required"` + Content BetaWebFetchToolResultBlockParamContentUnion `json:"content,omitzero" api:"required"` + ToolUseID string `json:"tool_use_id" api:"required"` // Create a cache control breakpoint at this content block. CacheControl BetaCacheControlEphemeralParam `json:"cache_control,omitzero"` // Tool invocation directly from the model. Caller BetaWebFetchToolResultBlockParamCallerUnion `json:"caller,omitzero"` // This field can be elided, and will marshal its zero value as // "web_fetch_tool_result". - Type constant.WebFetchToolResult `json:"type,required"` + Type constant.WebFetchToolResult `json:"type" api:"required"` paramObj } @@ -10094,21 +10103,12 @@ func (u BetaWebFetchToolResultBlockParamCallerUnion) GetToolID() *string { return nil } -func init() { - apijson.RegisterUnion[BetaWebFetchToolResultBlockParamCallerUnion]( - "type", - apijson.Discriminator[BetaDirectCallerParam]("direct"), - apijson.Discriminator[BetaServerToolCallerParam]("code_execution_20250825"), - apijson.Discriminator[BetaServerToolCaller20260120Param]("code_execution_20260120"), - ) -} - type BetaWebFetchToolResultErrorBlock struct { // Any of "invalid_tool_input", "url_too_long", "url_not_allowed", // "url_not_accessible", "unsupported_content_type", "too_many_requests", // "max_uses_exceeded", "unavailable". - ErrorCode BetaWebFetchToolResultErrorCode `json:"error_code,required"` - Type constant.WebFetchToolResultError `json:"type,required"` + ErrorCode BetaWebFetchToolResultErrorCode `json:"error_code" api:"required"` + Type constant.WebFetchToolResultError `json:"type" api:"required"` // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. JSON struct { ErrorCode respjson.Field @@ -10129,10 +10129,10 @@ type BetaWebFetchToolResultErrorBlockParam struct { // Any of "invalid_tool_input", "url_too_long", "url_not_allowed", // "url_not_accessible", "unsupported_content_type", "too_many_requests", // "max_uses_exceeded", "unavailable". - ErrorCode BetaWebFetchToolResultErrorCode `json:"error_code,omitzero,required"` + ErrorCode BetaWebFetchToolResultErrorCode `json:"error_code,omitzero" api:"required"` // This field can be elided, and will marshal its zero value as // "web_fetch_tool_result_error". - Type constant.WebFetchToolResultError `json:"type,required"` + Type constant.WebFetchToolResultError `json:"type" api:"required"` paramObj } @@ -10158,11 +10158,11 @@ const ( ) type BetaWebSearchResultBlock struct { - EncryptedContent string `json:"encrypted_content,required"` - PageAge string `json:"page_age,required"` - Title string `json:"title,required"` - Type constant.WebSearchResult `json:"type,required"` - URL string `json:"url,required"` + EncryptedContent string `json:"encrypted_content" api:"required"` + PageAge string `json:"page_age" api:"required"` + Title string `json:"title" api:"required"` + Type constant.WebSearchResult `json:"type" api:"required"` + URL string `json:"url" api:"required"` // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. JSON struct { EncryptedContent respjson.Field @@ -10183,13 +10183,13 @@ func (r *BetaWebSearchResultBlock) UnmarshalJSON(data []byte) error { // The properties EncryptedContent, Title, Type, URL are required. type BetaWebSearchResultBlockParam struct { - EncryptedContent string `json:"encrypted_content,required"` - Title string `json:"title,required"` - URL string `json:"url,required"` + EncryptedContent string `json:"encrypted_content" api:"required"` + Title string `json:"title" api:"required"` + URL string `json:"url" api:"required"` PageAge param.Opt[string] `json:"page_age,omitzero"` // This field can be elided, and will marshal its zero value as // "web_search_result". - Type constant.WebSearchResult `json:"type,required"` + Type constant.WebSearchResult `json:"type" api:"required"` paramObj } @@ -10228,10 +10228,10 @@ type BetaWebSearchTool20250305Param struct { // This is how the tool will be called by the model and in `tool_use` blocks. // // This field can be elided, and will marshal its zero value as "web_search". - Name constant.WebSearch `json:"name,required"` + Name constant.WebSearch `json:"name" api:"required"` // This field can be elided, and will marshal its zero value as // "web_search_20250305". - Type constant.WebSearch20250305 `json:"type,required"` + Type constant.WebSearch20250305 `json:"type" api:"required"` paramObj } @@ -10270,10 +10270,10 @@ type BetaWebSearchTool20260209Param struct { // This is how the tool will be called by the model and in `tool_use` blocks. // // This field can be elided, and will marshal its zero value as "web_search". - Name constant.WebSearch `json:"name,required"` + Name constant.WebSearch `json:"name" api:"required"` // This field can be elided, and will marshal its zero value as // "web_search_20260209". - Type constant.WebSearch20260209 `json:"type,required"` + Type constant.WebSearch20260209 `json:"type" api:"required"` paramObj } @@ -10289,10 +10289,10 @@ func (r *BetaWebSearchTool20260209Param) UnmarshalJSON(data []byte) error { type BetaWebSearchToolRequestErrorParam struct { // Any of "invalid_tool_input", "unavailable", "max_uses_exceeded", // "too_many_requests", "query_too_long", "request_too_large". - ErrorCode BetaWebSearchToolResultErrorCode `json:"error_code,omitzero,required"` + ErrorCode BetaWebSearchToolResultErrorCode `json:"error_code,omitzero" api:"required"` // This field can be elided, and will marshal its zero value as // "web_search_tool_result_error". - Type constant.WebSearchToolResultError `json:"type,required"` + Type constant.WebSearchToolResultError `json:"type" api:"required"` paramObj } @@ -10305,9 +10305,9 @@ func (r *BetaWebSearchToolRequestErrorParam) UnmarshalJSON(data []byte) error { } type BetaWebSearchToolResultBlock struct { - Content BetaWebSearchToolResultBlockContentUnion `json:"content,required"` - ToolUseID string `json:"tool_use_id,required"` - Type constant.WebSearchToolResult `json:"type,required"` + Content BetaWebSearchToolResultBlockContentUnion `json:"content" api:"required"` + ToolUseID string `json:"tool_use_id" api:"required"` + Type constant.WebSearchToolResult `json:"type" api:"required"` // Tool invocation directly from the model. Caller BetaWebSearchToolResultBlockCallerUnion `json:"caller"` // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. @@ -10442,15 +10442,15 @@ func (r *BetaWebSearchToolResultBlockContentUnion) UnmarshalJSON(data []byte) er // The properties Content, ToolUseID, Type are required. type BetaWebSearchToolResultBlockParam struct { - Content BetaWebSearchToolResultBlockParamContentUnion `json:"content,omitzero,required"` - ToolUseID string `json:"tool_use_id,required"` + Content BetaWebSearchToolResultBlockParamContentUnion `json:"content,omitzero" api:"required"` + ToolUseID string `json:"tool_use_id" api:"required"` // Create a cache control breakpoint at this content block. CacheControl BetaCacheControlEphemeralParam `json:"cache_control,omitzero"` // Tool invocation directly from the model. Caller BetaWebSearchToolResultBlockParamCallerUnion `json:"caller,omitzero"` // This field can be elided, and will marshal its zero value as // "web_search_tool_result". - Type constant.WebSearchToolResult `json:"type,required"` + Type constant.WebSearchToolResult `json:"type" api:"required"` paramObj } @@ -10512,15 +10512,6 @@ func (u BetaWebSearchToolResultBlockParamCallerUnion) GetToolID() *string { return nil } -func init() { - apijson.RegisterUnion[BetaWebSearchToolResultBlockParamCallerUnion]( - "type", - apijson.Discriminator[BetaDirectCallerParam]("direct"), - apijson.Discriminator[BetaServerToolCallerParam]("code_execution_20250825"), - apijson.Discriminator[BetaServerToolCaller20260120Param]("code_execution_20260120"), - ) -} - func BetaNewWebSearchToolRequestError(errorCode BetaWebSearchToolResultErrorCode) BetaWebSearchToolResultBlockParamContentUnion { var variant BetaWebSearchToolRequestErrorParam variant.ErrorCode = errorCode @@ -10555,8 +10546,8 @@ func (u *BetaWebSearchToolResultBlockParamContentUnion) asAny() any { type BetaWebSearchToolResultError struct { // Any of "invalid_tool_input", "unavailable", "max_uses_exceeded", // "too_many_requests", "query_too_long", "request_too_large". - ErrorCode BetaWebSearchToolResultErrorCode `json:"error_code,required"` - Type constant.WebSearchToolResultError `json:"type,required"` + ErrorCode BetaWebSearchToolResultErrorCode `json:"error_code" api:"required"` + Type constant.WebSearchToolResultError `json:"type" api:"required"` // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. JSON struct { ErrorCode respjson.Field @@ -10591,7 +10582,7 @@ type BetaMessageNewParams struct { // // Different models have different maximum values for this parameter. See // [models](https://docs.claude.com/en/docs/models-overview) for details. - MaxTokens int64 `json:"max_tokens,required"` + MaxTokens int64 `json:"max_tokens" api:"required"` // Input messages. // // Our models are trained to operate on alternating `user` and `assistant` @@ -10661,11 +10652,11 @@ type BetaMessageNewParams struct { // the Messages API. // // There is a limit of 100,000 messages in a single request. - Messages []BetaMessageParam `json:"messages,omitzero,required"` + Messages []BetaMessageParam `json:"messages,omitzero" api:"required"` // The model that will complete your prompt.\n\nSee // [models](https://docs.anthropic.com/en/docs/models-overview) for additional // details and options. - Model Model `json:"model,omitzero,required"` + Model Model `json:"model,omitzero" api:"required"` // Specifies the geographic region for inference processing. If not specified, the // workspace's `default_inference_geo` is used. InferenceGeo param.Opt[string] `json:"inference_geo,omitzero"` @@ -10971,11 +10962,11 @@ type BetaMessageCountTokensParams struct { // the Messages API. // // There is a limit of 100,000 messages in a single request. - Messages []BetaMessageParam `json:"messages,omitzero,required"` + Messages []BetaMessageParam `json:"messages,omitzero" api:"required"` // The model that will complete your prompt.\n\nSee // [models](https://docs.anthropic.com/en/docs/models-overview) for additional // details and options. - Model Model `json:"model,omitzero,required"` + Model Model `json:"model,omitzero" api:"required"` // The inference speed mode for this request. `"fast"` enables high // output-tokens-per-second inference. // @@ -11169,6 +11160,7 @@ type BetaMessageCountTokensParamsToolUnion struct { OfWebFetchTool20250910 *BetaWebFetchTool20250910Param `json:",omitzero,inline"` OfWebSearchTool20260209 *BetaWebSearchTool20260209Param `json:",omitzero,inline"` OfWebFetchTool20260209 *BetaWebFetchTool20260209Param `json:",omitzero,inline"` + OfWebFetchTool20260309 *BetaWebFetchTool20260309Param `json:",omitzero,inline"` OfToolSearchToolBm25_20251119 *BetaToolSearchToolBm25_20251119Param `json:",omitzero,inline"` OfToolSearchToolRegex20251119 *BetaToolSearchToolRegex20251119Param `json:",omitzero,inline"` OfMCPToolset *BetaMCPToolsetParam `json:",omitzero,inline"` @@ -11194,6 +11186,7 @@ func (u BetaMessageCountTokensParamsToolUnion) MarshalJSON() ([]byte, error) { u.OfWebFetchTool20250910, u.OfWebSearchTool20260209, u.OfWebFetchTool20260209, + u.OfWebFetchTool20260309, u.OfToolSearchToolBm25_20251119, u.OfToolSearchToolRegex20251119, u.OfMCPToolset) @@ -11239,6 +11232,8 @@ func (u *BetaMessageCountTokensParamsToolUnion) asAny() any { return u.OfWebSearchTool20260209 } else if !param.IsOmitted(u.OfWebFetchTool20260209) { return u.OfWebFetchTool20260209 + } else if !param.IsOmitted(u.OfWebFetchTool20260309) { + return u.OfWebFetchTool20260309 } else if !param.IsOmitted(u.OfToolSearchToolBm25_20251119) { return u.OfToolSearchToolBm25_20251119 } else if !param.IsOmitted(u.OfToolSearchToolRegex20251119) { @@ -11289,6 +11284,14 @@ func (u BetaMessageCountTokensParamsToolUnion) GetMaxCharacters() *int64 { return nil } +// Returns a pointer to the underlying variant's property, if present. +func (u BetaMessageCountTokensParamsToolUnion) GetUseCache() *bool { + if vt := u.OfWebFetchTool20260309; vt != nil && vt.UseCache.Valid() { + return &vt.UseCache.Value + } + return nil +} + // Returns a pointer to the underlying variant's property, if present. func (u BetaMessageCountTokensParamsToolUnion) GetMCPServerName() *string { if vt := u.OfMCPToolset; vt != nil { @@ -11351,6 +11354,8 @@ func (u BetaMessageCountTokensParamsToolUnion) GetName() *string { return (*string)(&vt.Name) } else if vt := u.OfWebFetchTool20260209; vt != nil { return (*string)(&vt.Name) + } else if vt := u.OfWebFetchTool20260309; vt != nil { + return (*string)(&vt.Name) } else if vt := u.OfToolSearchToolBm25_20251119; vt != nil { return (*string)(&vt.Name) } else if vt := u.OfToolSearchToolRegex20251119; vt != nil { @@ -11397,6 +11402,8 @@ func (u BetaMessageCountTokensParamsToolUnion) GetDeferLoading() *bool { return &vt.DeferLoading.Value } else if vt := u.OfWebFetchTool20260209; vt != nil && vt.DeferLoading.Valid() { return &vt.DeferLoading.Value + } else if vt := u.OfWebFetchTool20260309; vt != nil && vt.DeferLoading.Valid() { + return &vt.DeferLoading.Value } else if vt := u.OfToolSearchToolBm25_20251119; vt != nil && vt.DeferLoading.Valid() { return &vt.DeferLoading.Value } else if vt := u.OfToolSearchToolRegex20251119; vt != nil && vt.DeferLoading.Valid() { @@ -11443,6 +11450,8 @@ func (u BetaMessageCountTokensParamsToolUnion) GetStrict() *bool { return &vt.Strict.Value } else if vt := u.OfWebFetchTool20260209; vt != nil && vt.Strict.Valid() { return &vt.Strict.Value + } else if vt := u.OfWebFetchTool20260309; vt != nil && vt.Strict.Valid() { + return &vt.Strict.Value } else if vt := u.OfToolSearchToolBm25_20251119; vt != nil && vt.Strict.Valid() { return &vt.Strict.Value } else if vt := u.OfToolSearchToolRegex20251119; vt != nil && vt.Strict.Valid() { @@ -11489,6 +11498,8 @@ func (u BetaMessageCountTokensParamsToolUnion) GetType() *string { return (*string)(&vt.Type) } else if vt := u.OfWebFetchTool20260209; vt != nil { return (*string)(&vt.Type) + } else if vt := u.OfWebFetchTool20260309; vt != nil { + return (*string)(&vt.Type) } else if vt := u.OfToolSearchToolBm25_20251119; vt != nil { return (*string)(&vt.Type) } else if vt := u.OfToolSearchToolRegex20251119; vt != nil { @@ -11545,6 +11556,8 @@ func (u BetaMessageCountTokensParamsToolUnion) GetMaxUses() *int64 { return &vt.MaxUses.Value } else if vt := u.OfWebFetchTool20260209; vt != nil && vt.MaxUses.Valid() { return &vt.MaxUses.Value + } else if vt := u.OfWebFetchTool20260309; vt != nil && vt.MaxUses.Valid() { + return &vt.MaxUses.Value } return nil } @@ -11555,6 +11568,8 @@ func (u BetaMessageCountTokensParamsToolUnion) GetMaxContentTokens() *int64 { return &vt.MaxContentTokens.Value } else if vt := u.OfWebFetchTool20260209; vt != nil && vt.MaxContentTokens.Valid() { return &vt.MaxContentTokens.Value + } else if vt := u.OfWebFetchTool20260309; vt != nil && vt.MaxContentTokens.Valid() { + return &vt.MaxContentTokens.Value } return nil } @@ -11598,6 +11613,8 @@ func (u BetaMessageCountTokensParamsToolUnion) GetAllowedCallers() []string { return vt.AllowedCallers } else if vt := u.OfWebFetchTool20260209; vt != nil { return vt.AllowedCallers + } else if vt := u.OfWebFetchTool20260309; vt != nil { + return vt.AllowedCallers } else if vt := u.OfToolSearchToolBm25_20251119; vt != nil { return vt.AllowedCallers } else if vt := u.OfToolSearchToolRegex20251119; vt != nil { @@ -11644,6 +11661,8 @@ func (u BetaMessageCountTokensParamsToolUnion) GetCacheControl() *BetaCacheContr return &vt.CacheControl } else if vt := u.OfWebFetchTool20260209; vt != nil { return &vt.CacheControl + } else if vt := u.OfWebFetchTool20260309; vt != nil { + return &vt.CacheControl } else if vt := u.OfToolSearchToolBm25_20251119; vt != nil { return &vt.CacheControl } else if vt := u.OfToolSearchToolRegex20251119; vt != nil { @@ -11694,6 +11713,8 @@ func (u BetaMessageCountTokensParamsToolUnion) GetAllowedDomains() []string { return vt.AllowedDomains } else if vt := u.OfWebFetchTool20260209; vt != nil { return vt.AllowedDomains + } else if vt := u.OfWebFetchTool20260309; vt != nil { + return vt.AllowedDomains } return nil } @@ -11709,6 +11730,8 @@ func (u BetaMessageCountTokensParamsToolUnion) GetBlockedDomains() []string { return vt.BlockedDomains } else if vt := u.OfWebFetchTool20260209; vt != nil { return vt.BlockedDomains + } else if vt := u.OfWebFetchTool20260309; vt != nil { + return vt.BlockedDomains } return nil } @@ -11729,6 +11752,8 @@ func (u BetaMessageCountTokensParamsToolUnion) GetCitations() *BetaCitationsConf return &vt.Citations } else if vt := u.OfWebFetchTool20260209; vt != nil { return &vt.Citations + } else if vt := u.OfWebFetchTool20260309; vt != nil { + return &vt.Citations } return nil } diff --git a/betamessage_test.go b/betamessage_test.go index 7800428f..d5330b46 100644 --- a/betamessage_test.go +++ b/betamessage_test.go @@ -15,7 +15,6 @@ import ( ) func TestBetaMessageNewWithOptionalParams(t *testing.T) { - t.Skip("prism validates based on the non-beta endpoint") baseURL := "http://localhost:4010" if envURL, ok := os.LookupEnv("TEST_API_BASE_URL"); ok { baseURL = envURL @@ -130,8 +129,8 @@ func TestBetaMessageNewWithOptionalParams(t *testing.T) { }}, Temperature: anthropic.Float(1), Thinking: anthropic.BetaThinkingConfigParamUnion{ - OfEnabled: &anthropic.BetaThinkingConfigEnabledParam{ - BudgetTokens: 1024, + OfAdaptive: &anthropic.BetaThinkingConfigAdaptiveParam{ + Display: anthropic.BetaThinkingConfigAdaptiveDisplaySummarized, }, }, ToolChoice: anthropic.BetaToolChoiceUnionParam{ @@ -177,7 +176,6 @@ func TestBetaMessageNewWithOptionalParams(t *testing.T) { } func TestBetaMessageCountTokensWithOptionalParams(t *testing.T) { - t.Skip("prism validates based on the non-beta endpoint") baseURL := "http://localhost:4010" if envURL, ok := os.LookupEnv("TEST_API_BASE_URL"); ok { baseURL = envURL @@ -276,8 +274,8 @@ func TestBetaMessageCountTokensWithOptionalParams(t *testing.T) { }}, }, Thinking: anthropic.BetaThinkingConfigParamUnion{ - OfEnabled: &anthropic.BetaThinkingConfigEnabledParam{ - BudgetTokens: 1024, + OfAdaptive: &anthropic.BetaThinkingConfigAdaptiveParam{ + Display: anthropic.BetaThinkingConfigAdaptiveDisplaySummarized, }, }, ToolChoice: anthropic.BetaToolChoiceUnionParam{ diff --git a/betamessagebatch.go b/betamessagebatch.go index b4dc2f4f..68ce62d4 100644 --- a/betamessagebatch.go +++ b/betamessagebatch.go @@ -58,7 +58,7 @@ func (r *BetaMessageBatchService) New(ctx context.Context, params BetaMessageBat opts = append([]option.RequestOption{option.WithHeader("anthropic-beta", "message-batches-2024-09-24")}, opts...) path := "v1/messages/batches?beta=true" err = requestconfig.ExecuteNewRequest(ctx, http.MethodPost, path, params, &res, opts...) - return + return res, err } // This endpoint is idempotent and can be used to poll for Message Batch @@ -75,11 +75,11 @@ func (r *BetaMessageBatchService) Get(ctx context.Context, messageBatchID string opts = append([]option.RequestOption{option.WithHeader("anthropic-beta", "message-batches-2024-09-24")}, opts...) if messageBatchID == "" { err = errors.New("missing required message_batch_id parameter") - return + return nil, err } path := fmt.Sprintf("v1/messages/batches/%s?beta=true", messageBatchID) err = requestconfig.ExecuteNewRequest(ctx, http.MethodGet, path, nil, &res, opts...) - return + return res, err } // List all Message Batches within a Workspace. Most recently created batches are @@ -131,11 +131,11 @@ func (r *BetaMessageBatchService) Delete(ctx context.Context, messageBatchID str opts = append([]option.RequestOption{option.WithHeader("anthropic-beta", "message-batches-2024-09-24")}, opts...) if messageBatchID == "" { err = errors.New("missing required message_batch_id parameter") - return + return nil, err } path := fmt.Sprintf("v1/messages/batches/%s?beta=true", messageBatchID) err = requestconfig.ExecuteNewRequest(ctx, http.MethodDelete, path, nil, &res, opts...) - return + return res, err } // Batches may be canceled any time before processing ends. Once cancellation is @@ -158,11 +158,11 @@ func (r *BetaMessageBatchService) Cancel(ctx context.Context, messageBatchID str opts = append([]option.RequestOption{option.WithHeader("anthropic-beta", "message-batches-2024-09-24")}, opts...) if messageBatchID == "" { err = errors.New("missing required message_batch_id parameter") - return + return nil, err } path := fmt.Sprintf("v1/messages/batches/%s/cancel?beta=true", messageBatchID) err = requestconfig.ExecuteNewRequest(ctx, http.MethodPost, path, nil, &res, opts...) - return + return res, err } // Streams the results of a Message Batch as a `.jsonl` file. @@ -185,7 +185,7 @@ func (r *BetaMessageBatchService) ResultsStreaming(ctx context.Context, messageB opts = append([]option.RequestOption{option.WithHeader("anthropic-beta", "message-batches-2024-09-24"), option.WithHeader("Accept", "application/x-jsonl")}, opts...) if messageBatchID == "" { err = errors.New("missing required message_batch_id parameter") - return + return jsonl.NewStream[BetaMessageBatchIndividualResponse](nil, err) } path := fmt.Sprintf("v1/messages/batches/%s/results?beta=true", messageBatchID) err = requestconfig.ExecuteNewRequest(ctx, http.MethodGet, path, nil, &raw, opts...) @@ -194,11 +194,11 @@ func (r *BetaMessageBatchService) ResultsStreaming(ctx context.Context, messageB type BetaDeletedMessageBatch struct { // ID of the Message Batch. - ID string `json:"id,required"` + ID string `json:"id" api:"required"` // Deleted object type. // // For Message Batches, this is always `"message_batch_deleted"`. - Type constant.MessageBatchDeleted `json:"type,required"` + Type constant.MessageBatchDeleted `json:"type" api:"required"` // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. JSON struct { ID respjson.Field @@ -218,45 +218,45 @@ type BetaMessageBatch struct { // Unique object identifier. // // The format and length of IDs may change over time. - ID string `json:"id,required"` + ID string `json:"id" api:"required"` // RFC 3339 datetime string representing the time at which the Message Batch was // archived and its results became unavailable. - ArchivedAt time.Time `json:"archived_at,required" format:"date-time"` + ArchivedAt time.Time `json:"archived_at" api:"required" format:"date-time"` // RFC 3339 datetime string representing the time at which cancellation was // initiated for the Message Batch. Specified only if cancellation was initiated. - CancelInitiatedAt time.Time `json:"cancel_initiated_at,required" format:"date-time"` + CancelInitiatedAt time.Time `json:"cancel_initiated_at" api:"required" format:"date-time"` // RFC 3339 datetime string representing the time at which the Message Batch was // created. - CreatedAt time.Time `json:"created_at,required" format:"date-time"` + CreatedAt time.Time `json:"created_at" api:"required" format:"date-time"` // RFC 3339 datetime string representing the time at which processing for the // Message Batch ended. Specified only once processing ends. // // Processing ends when every request in a Message Batch has either succeeded, // errored, canceled, or expired. - EndedAt time.Time `json:"ended_at,required" format:"date-time"` + EndedAt time.Time `json:"ended_at" api:"required" format:"date-time"` // RFC 3339 datetime string representing the time at which the Message Batch will // expire and end processing, which is 24 hours after creation. - ExpiresAt time.Time `json:"expires_at,required" format:"date-time"` + ExpiresAt time.Time `json:"expires_at" api:"required" format:"date-time"` // Processing status of the Message Batch. // // Any of "in_progress", "canceling", "ended". - ProcessingStatus BetaMessageBatchProcessingStatus `json:"processing_status,required"` + ProcessingStatus BetaMessageBatchProcessingStatus `json:"processing_status" api:"required"` // Tallies requests within the Message Batch, categorized by their status. // // Requests start as `processing` and move to one of the other statuses only once // processing of the entire batch ends. The sum of all values always matches the // total number of requests in the batch. - RequestCounts BetaMessageBatchRequestCounts `json:"request_counts,required"` + RequestCounts BetaMessageBatchRequestCounts `json:"request_counts" api:"required"` // URL to a `.jsonl` file containing the results of the Message Batch requests. // Specified only once processing ends. // // Results in the file are not guaranteed to be in the same order as requests. Use // the `custom_id` field to match results to requests. - ResultsURL string `json:"results_url,required"` + ResultsURL string `json:"results_url" api:"required"` // Object type. // // For Message Batches, this is always `"message_batch"`. - Type constant.MessageBatch `json:"type,required"` + Type constant.MessageBatch `json:"type" api:"required"` // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. JSON struct { ID respjson.Field @@ -290,7 +290,7 @@ const ( ) type BetaMessageBatchCanceledResult struct { - Type constant.Canceled `json:"type,required"` + Type constant.Canceled `json:"type" api:"required"` // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. JSON struct { Type respjson.Field @@ -306,8 +306,8 @@ func (r *BetaMessageBatchCanceledResult) UnmarshalJSON(data []byte) error { } type BetaMessageBatchErroredResult struct { - Error BetaErrorResponse `json:"error,required"` - Type constant.Errored `json:"type,required"` + Error BetaErrorResponse `json:"error" api:"required"` + Type constant.Errored `json:"type" api:"required"` // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. JSON struct { Error respjson.Field @@ -324,7 +324,7 @@ func (r *BetaMessageBatchErroredResult) UnmarshalJSON(data []byte) error { } type BetaMessageBatchExpiredResult struct { - Type constant.Expired `json:"type,required"` + Type constant.Expired `json:"type" api:"required"` // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. JSON struct { Type respjson.Field @@ -346,13 +346,13 @@ type BetaMessageBatchIndividualResponse struct { // matching results to requests, as results may be given out of request order. // // Must be unique for each request within the Message Batch. - CustomID string `json:"custom_id,required"` + CustomID string `json:"custom_id" api:"required"` // Processing result for this request. // // Contains a Message output if processing was successful, an error response if // processing failed, or the reason why processing was not attempted, such as // cancellation or expiration. - Result BetaMessageBatchResultUnion `json:"result,required"` + Result BetaMessageBatchResultUnion `json:"result" api:"required"` // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. JSON struct { CustomID respjson.Field @@ -372,21 +372,21 @@ type BetaMessageBatchRequestCounts struct { // Number of requests in the Message Batch that have been canceled. // // This is zero until processing of the entire Message Batch has ended. - Canceled int64 `json:"canceled,required"` + Canceled int64 `json:"canceled" api:"required"` // Number of requests in the Message Batch that encountered an error. // // This is zero until processing of the entire Message Batch has ended. - Errored int64 `json:"errored,required"` + Errored int64 `json:"errored" api:"required"` // Number of requests in the Message Batch that have expired. // // This is zero until processing of the entire Message Batch has ended. - Expired int64 `json:"expired,required"` + Expired int64 `json:"expired" api:"required"` // Number of requests in the Message Batch that are processing. - Processing int64 `json:"processing,required"` + Processing int64 `json:"processing" api:"required"` // Number of requests in the Message Batch that have completed successfully. // // This is zero until processing of the entire Message Batch has ended. - Succeeded int64 `json:"succeeded,required"` + Succeeded int64 `json:"succeeded" api:"required"` // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. JSON struct { Canceled respjson.Field @@ -491,8 +491,8 @@ func (r *BetaMessageBatchResultUnion) UnmarshalJSON(data []byte) error { } type BetaMessageBatchSucceededResult struct { - Message BetaMessage `json:"message,required"` - Type constant.Succeeded `json:"type,required"` + Message BetaMessage `json:"message" api:"required"` + Type constant.Succeeded `json:"type" api:"required"` // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. JSON struct { Message respjson.Field @@ -511,7 +511,7 @@ func (r *BetaMessageBatchSucceededResult) UnmarshalJSON(data []byte) error { type BetaMessageBatchNewParams struct { // List of requests for prompt completion. Each is an individual request to create // a Message. - Requests []BetaMessageBatchNewParamsRequest `json:"requests,omitzero,required"` + Requests []BetaMessageBatchNewParamsRequest `json:"requests,omitzero" api:"required"` // Optional header to specify the beta version(s) you want to use. Betas []AnthropicBeta `header:"anthropic-beta,omitzero" json:"-"` paramObj @@ -531,12 +531,12 @@ type BetaMessageBatchNewParamsRequest struct { // matching results to requests, as results may be given out of request order. // // Must be unique for each request within the Message Batch. - CustomID string `json:"custom_id,required"` + CustomID string `json:"custom_id" api:"required"` // Messages API creation parameters for the individual request. // // See the [Messages API reference](https://docs.claude.com/en/api/messages) for // full documentation on available parameters. - Params BetaMessageBatchNewParamsRequestParams `json:"params,omitzero,required"` + Params BetaMessageBatchNewParamsRequestParams `json:"params,omitzero" api:"required"` paramObj } @@ -562,7 +562,7 @@ type BetaMessageBatchNewParamsRequestParams struct { // // Different models have different maximum values for this parameter. See // [models](https://docs.claude.com/en/docs/models-overview) for details. - MaxTokens int64 `json:"max_tokens,required"` + MaxTokens int64 `json:"max_tokens" api:"required"` // Input messages. // // Our models are trained to operate on alternating `user` and `assistant` @@ -632,11 +632,11 @@ type BetaMessageBatchNewParamsRequestParams struct { // the Messages API. // // There is a limit of 100,000 messages in a single request. - Messages []BetaMessageParam `json:"messages,omitzero,required"` + Messages []BetaMessageParam `json:"messages,omitzero" api:"required"` // The model that will complete your prompt.\n\nSee // [models](https://docs.anthropic.com/en/docs/models-overview) for additional // details and options. - Model Model `json:"model,omitzero,required"` + Model Model `json:"model,omitzero" api:"required"` // Specifies the geographic region for inference processing. If not specified, the // workspace's `default_inference_geo` is used. InferenceGeo param.Opt[string] `json:"inference_geo,omitzero"` diff --git a/betamessagebatch_test.go b/betamessagebatch_test.go index bd69b8a2..bd26c10f 100644 --- a/betamessagebatch_test.go +++ b/betamessagebatch_test.go @@ -14,7 +14,6 @@ import ( ) func TestBetaMessageBatchNewWithOptionalParams(t *testing.T) { - t.Skip("prism validates based on the non-beta endpoint") baseURL := "http://localhost:4010" if envURL, ok := os.LookupEnv("TEST_API_BASE_URL"); ok { baseURL = envURL @@ -133,8 +132,8 @@ func TestBetaMessageBatchNewWithOptionalParams(t *testing.T) { }}, Temperature: anthropic.Float(1), Thinking: anthropic.BetaThinkingConfigParamUnion{ - OfEnabled: &anthropic.BetaThinkingConfigEnabledParam{ - BudgetTokens: 1024, + OfAdaptive: &anthropic.BetaThinkingConfigAdaptiveParam{ + Display: anthropic.BetaThinkingConfigAdaptiveDisplaySummarized, }, }, ToolChoice: anthropic.BetaToolChoiceUnionParam{ diff --git a/betamodel.go b/betamodel.go index 863a5a04..a5df8425 100644 --- a/betamodel.go +++ b/betamodel.go @@ -51,11 +51,11 @@ func (r *BetaModelService) Get(ctx context.Context, modelID string, query BetaMo opts = slices.Concat(r.Options, opts) if modelID == "" { err = errors.New("missing required model_id parameter") - return + return nil, err } path := fmt.Sprintf("v1/models/%s?beta=true", modelID) err = requestconfig.ExecuteNewRequest(ctx, http.MethodGet, path, nil, &res, opts...) - return + return res, err } // List available models. @@ -92,16 +92,16 @@ func (r *BetaModelService) ListAutoPaging(ctx context.Context, params BetaModelL type BetaModelInfo struct { // Unique model identifier. - ID string `json:"id,required"` + ID string `json:"id" api:"required"` // RFC 3339 datetime string representing the time at which the model was released. // May be set to an epoch value if the release date is unknown. - CreatedAt time.Time `json:"created_at,required" format:"date-time"` + CreatedAt time.Time `json:"created_at" api:"required" format:"date-time"` // A human-readable name for the model. - DisplayName string `json:"display_name,required"` + DisplayName string `json:"display_name" api:"required"` // Object type. // // For Models, this is always `"model"`. - Type constant.Model `json:"type,required"` + Type constant.Model `json:"type" api:"required"` // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. JSON struct { ID respjson.Field diff --git a/betaskill.go b/betaskill.go index 66f3f043..1dd9dc9c 100644 --- a/betaskill.go +++ b/betaskill.go @@ -53,7 +53,7 @@ func (r *BetaSkillService) New(ctx context.Context, params BetaSkillNewParams, o opts = append([]option.RequestOption{option.WithHeader("anthropic-beta", "skills-2025-10-02")}, opts...) path := "v1/skills?beta=true" err = requestconfig.ExecuteNewRequest(ctx, http.MethodPost, path, params, &res, opts...) - return + return res, err } // Get Skill @@ -65,11 +65,11 @@ func (r *BetaSkillService) Get(ctx context.Context, skillID string, query BetaSk opts = append([]option.RequestOption{option.WithHeader("anthropic-beta", "skills-2025-10-02")}, opts...) if skillID == "" { err = errors.New("missing required skill_id parameter") - return + return nil, err } path := fmt.Sprintf("v1/skills/%s?beta=true", skillID) err = requestconfig.ExecuteNewRequest(ctx, http.MethodGet, path, nil, &res, opts...) - return + return res, err } // List Skills @@ -107,42 +107,42 @@ func (r *BetaSkillService) Delete(ctx context.Context, skillID string, body Beta opts = append([]option.RequestOption{option.WithHeader("anthropic-beta", "skills-2025-10-02")}, opts...) if skillID == "" { err = errors.New("missing required skill_id parameter") - return + return nil, err } path := fmt.Sprintf("v1/skills/%s?beta=true", skillID) err = requestconfig.ExecuteNewRequest(ctx, http.MethodDelete, path, nil, &res, opts...) - return + return res, err } type BetaSkillNewResponse struct { // Unique identifier for the skill. // // The format and length of IDs may change over time. - ID string `json:"id,required"` + ID string `json:"id" api:"required"` // ISO 8601 timestamp of when the skill was created. - CreatedAt string `json:"created_at,required"` + CreatedAt string `json:"created_at" api:"required"` // Display title for the skill. // // This is a human-readable label that is not included in the prompt sent to the // model. - DisplayTitle string `json:"display_title,required"` + DisplayTitle string `json:"display_title" api:"required"` // The latest version identifier for the skill. // // This represents the most recent version of the skill that has been created. - LatestVersion string `json:"latest_version,required"` + LatestVersion string `json:"latest_version" api:"required"` // Source of the skill. // // This may be one of the following values: // // - `"custom"`: the skill was created by a user // - `"anthropic"`: the skill was created by Anthropic - Source string `json:"source,required"` + Source string `json:"source" api:"required"` // Object type. // // For Skills, this is always `"skill"`. - Type string `json:"type,required"` + Type string `json:"type" api:"required"` // ISO 8601 timestamp of when the skill was last updated. - UpdatedAt string `json:"updated_at,required"` + UpdatedAt string `json:"updated_at" api:"required"` // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. JSON struct { ID respjson.Field @@ -167,31 +167,31 @@ type BetaSkillGetResponse struct { // Unique identifier for the skill. // // The format and length of IDs may change over time. - ID string `json:"id,required"` + ID string `json:"id" api:"required"` // ISO 8601 timestamp of when the skill was created. - CreatedAt string `json:"created_at,required"` + CreatedAt string `json:"created_at" api:"required"` // Display title for the skill. // // This is a human-readable label that is not included in the prompt sent to the // model. - DisplayTitle string `json:"display_title,required"` + DisplayTitle string `json:"display_title" api:"required"` // The latest version identifier for the skill. // // This represents the most recent version of the skill that has been created. - LatestVersion string `json:"latest_version,required"` + LatestVersion string `json:"latest_version" api:"required"` // Source of the skill. // // This may be one of the following values: // // - `"custom"`: the skill was created by a user // - `"anthropic"`: the skill was created by Anthropic - Source string `json:"source,required"` + Source string `json:"source" api:"required"` // Object type. // // For Skills, this is always `"skill"`. - Type string `json:"type,required"` + Type string `json:"type" api:"required"` // ISO 8601 timestamp of when the skill was last updated. - UpdatedAt string `json:"updated_at,required"` + UpdatedAt string `json:"updated_at" api:"required"` // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. JSON struct { ID respjson.Field @@ -216,31 +216,31 @@ type BetaSkillListResponse struct { // Unique identifier for the skill. // // The format and length of IDs may change over time. - ID string `json:"id,required"` + ID string `json:"id" api:"required"` // ISO 8601 timestamp of when the skill was created. - CreatedAt string `json:"created_at,required"` + CreatedAt string `json:"created_at" api:"required"` // Display title for the skill. // // This is a human-readable label that is not included in the prompt sent to the // model. - DisplayTitle string `json:"display_title,required"` + DisplayTitle string `json:"display_title" api:"required"` // The latest version identifier for the skill. // // This represents the most recent version of the skill that has been created. - LatestVersion string `json:"latest_version,required"` + LatestVersion string `json:"latest_version" api:"required"` // Source of the skill. // // This may be one of the following values: // // - `"custom"`: the skill was created by a user // - `"anthropic"`: the skill was created by Anthropic - Source string `json:"source,required"` + Source string `json:"source" api:"required"` // Object type. // // For Skills, this is always `"skill"`. - Type string `json:"type,required"` + Type string `json:"type" api:"required"` // ISO 8601 timestamp of when the skill was last updated. - UpdatedAt string `json:"updated_at,required"` + UpdatedAt string `json:"updated_at" api:"required"` // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. JSON struct { ID respjson.Field @@ -265,11 +265,11 @@ type BetaSkillDeleteResponse struct { // Unique identifier for the skill. // // The format and length of IDs may change over time. - ID string `json:"id,required"` + ID string `json:"id" api:"required"` // Deleted object type. // // For Skills, this is always `"skill_deleted"`. - Type string `json:"type,required"` + Type string `json:"type" api:"required"` // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. JSON struct { ID respjson.Field diff --git a/betaskill_test.go b/betaskill_test.go index cc0d3124..d5ef3672 100644 --- a/betaskill_test.go +++ b/betaskill_test.go @@ -16,7 +16,6 @@ import ( ) func TestBetaSkillNewWithOptionalParams(t *testing.T) { - t.Skip("prism binary unsupported") baseURL := "http://localhost:4010" if envURL, ok := os.LookupEnv("TEST_API_BASE_URL"); ok { baseURL = envURL @@ -30,7 +29,7 @@ func TestBetaSkillNewWithOptionalParams(t *testing.T) { ) _, err := client.Beta.Skills.New(context.TODO(), anthropic.BetaSkillNewParams{ DisplayTitle: anthropic.String("display_title"), - Files: []io.Reader{io.Reader(bytes.NewBuffer([]byte("some file contents")))}, + Files: []io.Reader{io.Reader(bytes.NewBuffer([]byte("Example data")))}, Betas: []anthropic.AnthropicBeta{anthropic.AnthropicBetaMessageBatches2024_09_24}, }) if err != nil { diff --git a/betaskillversion.go b/betaskillversion.go index 26115cc7..dabce4f1 100644 --- a/betaskillversion.go +++ b/betaskillversion.go @@ -51,11 +51,11 @@ func (r *BetaSkillVersionService) New(ctx context.Context, skillID string, param opts = append([]option.RequestOption{option.WithHeader("anthropic-beta", "skills-2025-10-02")}, opts...) if skillID == "" { err = errors.New("missing required skill_id parameter") - return + return nil, err } path := fmt.Sprintf("v1/skills/%s/versions?beta=true", skillID) err = requestconfig.ExecuteNewRequest(ctx, http.MethodPost, path, params, &res, opts...) - return + return res, err } // Get Skill Version @@ -67,15 +67,15 @@ func (r *BetaSkillVersionService) Get(ctx context.Context, version string, param opts = append([]option.RequestOption{option.WithHeader("anthropic-beta", "skills-2025-10-02")}, opts...) if params.SkillID == "" { err = errors.New("missing required skill_id parameter") - return + return nil, err } if version == "" { err = errors.New("missing required version parameter") - return + return nil, err } path := fmt.Sprintf("v1/skills/%s/versions/%s?beta=true", params.SkillID, version) err = requestconfig.ExecuteNewRequest(ctx, http.MethodGet, path, nil, &res, opts...) - return + return res, err } // List Skill Versions @@ -88,7 +88,7 @@ func (r *BetaSkillVersionService) List(ctx context.Context, skillID string, para opts = append([]option.RequestOption{option.WithHeader("anthropic-beta", "skills-2025-10-02"), option.WithResponseInto(&raw)}, opts...) if skillID == "" { err = errors.New("missing required skill_id parameter") - return + return nil, err } path := fmt.Sprintf("v1/skills/%s/versions?beta=true", skillID) cfg, err := requestconfig.NewRequestConfig(ctx, http.MethodGet, path, params, &res, opts...) @@ -117,46 +117,46 @@ func (r *BetaSkillVersionService) Delete(ctx context.Context, version string, pa opts = append([]option.RequestOption{option.WithHeader("anthropic-beta", "skills-2025-10-02")}, opts...) if params.SkillID == "" { err = errors.New("missing required skill_id parameter") - return + return nil, err } if version == "" { err = errors.New("missing required version parameter") - return + return nil, err } path := fmt.Sprintf("v1/skills/%s/versions/%s?beta=true", params.SkillID, version) err = requestconfig.ExecuteNewRequest(ctx, http.MethodDelete, path, nil, &res, opts...) - return + return res, err } type BetaSkillVersionNewResponse struct { // Unique identifier for the skill version. // // The format and length of IDs may change over time. - ID string `json:"id,required"` + ID string `json:"id" api:"required"` // ISO 8601 timestamp of when the skill version was created. - CreatedAt string `json:"created_at,required"` + CreatedAt string `json:"created_at" api:"required"` // Description of the skill version. // // This is extracted from the SKILL.md file in the skill upload. - Description string `json:"description,required"` + Description string `json:"description" api:"required"` // Directory name of the skill version. // // This is the top-level directory name that was extracted from the uploaded files. - Directory string `json:"directory,required"` + Directory string `json:"directory" api:"required"` // Human-readable name of the skill version. // // This is extracted from the SKILL.md file in the skill upload. - Name string `json:"name,required"` + Name string `json:"name" api:"required"` // Identifier for the skill that this version belongs to. - SkillID string `json:"skill_id,required"` + SkillID string `json:"skill_id" api:"required"` // Object type. // // For Skill Versions, this is always `"skill_version"`. - Type string `json:"type,required"` + Type string `json:"type" api:"required"` // Version identifier for the skill. // // Each version is identified by a Unix epoch timestamp (e.g., "1759178010641129"). - Version string `json:"version,required"` + Version string `json:"version" api:"required"` // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. JSON struct { ID respjson.Field @@ -182,31 +182,31 @@ type BetaSkillVersionGetResponse struct { // Unique identifier for the skill version. // // The format and length of IDs may change over time. - ID string `json:"id,required"` + ID string `json:"id" api:"required"` // ISO 8601 timestamp of when the skill version was created. - CreatedAt string `json:"created_at,required"` + CreatedAt string `json:"created_at" api:"required"` // Description of the skill version. // // This is extracted from the SKILL.md file in the skill upload. - Description string `json:"description,required"` + Description string `json:"description" api:"required"` // Directory name of the skill version. // // This is the top-level directory name that was extracted from the uploaded files. - Directory string `json:"directory,required"` + Directory string `json:"directory" api:"required"` // Human-readable name of the skill version. // // This is extracted from the SKILL.md file in the skill upload. - Name string `json:"name,required"` + Name string `json:"name" api:"required"` // Identifier for the skill that this version belongs to. - SkillID string `json:"skill_id,required"` + SkillID string `json:"skill_id" api:"required"` // Object type. // // For Skill Versions, this is always `"skill_version"`. - Type string `json:"type,required"` + Type string `json:"type" api:"required"` // Version identifier for the skill. // // Each version is identified by a Unix epoch timestamp (e.g., "1759178010641129"). - Version string `json:"version,required"` + Version string `json:"version" api:"required"` // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. JSON struct { ID respjson.Field @@ -232,31 +232,31 @@ type BetaSkillVersionListResponse struct { // Unique identifier for the skill version. // // The format and length of IDs may change over time. - ID string `json:"id,required"` + ID string `json:"id" api:"required"` // ISO 8601 timestamp of when the skill version was created. - CreatedAt string `json:"created_at,required"` + CreatedAt string `json:"created_at" api:"required"` // Description of the skill version. // // This is extracted from the SKILL.md file in the skill upload. - Description string `json:"description,required"` + Description string `json:"description" api:"required"` // Directory name of the skill version. // // This is the top-level directory name that was extracted from the uploaded files. - Directory string `json:"directory,required"` + Directory string `json:"directory" api:"required"` // Human-readable name of the skill version. // // This is extracted from the SKILL.md file in the skill upload. - Name string `json:"name,required"` + Name string `json:"name" api:"required"` // Identifier for the skill that this version belongs to. - SkillID string `json:"skill_id,required"` + SkillID string `json:"skill_id" api:"required"` // Object type. // // For Skill Versions, this is always `"skill_version"`. - Type string `json:"type,required"` + Type string `json:"type" api:"required"` // Version identifier for the skill. // // Each version is identified by a Unix epoch timestamp (e.g., "1759178010641129"). - Version string `json:"version,required"` + Version string `json:"version" api:"required"` // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. JSON struct { ID respjson.Field @@ -282,11 +282,11 @@ type BetaSkillVersionDeleteResponse struct { // Version identifier for the skill. // // Each version is identified by a Unix epoch timestamp (e.g., "1759178010641129"). - ID string `json:"id,required"` + ID string `json:"id" api:"required"` // Deleted object type. // // For Skill Versions, this is always `"skill_version_deleted"`. - Type string `json:"type,required"` + Type string `json:"type" api:"required"` // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. JSON struct { ID respjson.Field @@ -335,7 +335,7 @@ type BetaSkillVersionGetParams struct { // Unique identifier for the skill. // // The format and length of IDs may change over time. - SkillID string `path:"skill_id,required" json:"-"` + SkillID string `path:"skill_id" api:"required" json:"-"` // Optional header to specify the beta version(s) you want to use. Betas []AnthropicBeta `header:"anthropic-beta,omitzero" json:"-"` paramObj @@ -366,7 +366,7 @@ type BetaSkillVersionDeleteParams struct { // Unique identifier for the skill. // // The format and length of IDs may change over time. - SkillID string `path:"skill_id,required" json:"-"` + SkillID string `path:"skill_id" api:"required" json:"-"` // Optional header to specify the beta version(s) you want to use. Betas []AnthropicBeta `header:"anthropic-beta,omitzero" json:"-"` paramObj diff --git a/betaskillversion_test.go b/betaskillversion_test.go index b4825491..2288fad6 100644 --- a/betaskillversion_test.go +++ b/betaskillversion_test.go @@ -16,7 +16,6 @@ import ( ) func TestBetaSkillVersionNewWithOptionalParams(t *testing.T) { - t.Skip("prism binary unsupported") baseURL := "http://localhost:4010" if envURL, ok := os.LookupEnv("TEST_API_BASE_URL"); ok { baseURL = envURL @@ -32,7 +31,7 @@ func TestBetaSkillVersionNewWithOptionalParams(t *testing.T) { context.TODO(), "skill_id", anthropic.BetaSkillVersionNewParams{ - Files: []io.Reader{io.Reader(bytes.NewBuffer([]byte("some file contents")))}, + Files: []io.Reader{io.Reader(bytes.NewBuffer([]byte("Example data")))}, Betas: []anthropic.AnthropicBeta{anthropic.AnthropicBetaMessageBatches2024_09_24}, }, ) diff --git a/client_test.go b/client_test.go index 67a67617..5b325452 100644 --- a/client_test.go +++ b/client_test.go @@ -39,7 +39,7 @@ func TestUserAgentHeader(t *testing.T) { }, }), ) - client.Messages.New(context.Background(), anthropic.MessageNewParams{ + _, _ = client.Messages.New(context.Background(), anthropic.MessageNewParams{ MaxTokens: 1024, Messages: []anthropic.MessageParam{{ Content: []anthropic.ContentBlockParamUnion{{ diff --git a/completion.go b/completion.go index beaf526c..c65c6d5a 100644 --- a/completion.go +++ b/completion.go @@ -53,7 +53,7 @@ func (r *CompletionService) New(ctx context.Context, params CompletionNewParams, opts = slices.Concat(r.Options, opts) path := "v1/complete" err = requestconfig.ExecuteNewRequest(ctx, http.MethodPost, path, params, &res, opts...) - return + return res, err } // [Legacy] Create a Text Completion. @@ -85,13 +85,13 @@ type Completion struct { // Unique object identifier. // // The format and length of IDs may change over time. - ID string `json:"id,required"` + ID string `json:"id" api:"required"` // The resulting completion up to and excluding the stop sequences. - Completion string `json:"completion,required"` + Completion string `json:"completion" api:"required"` // The model that will complete your prompt.\n\nSee // [models](https://docs.anthropic.com/en/docs/models-overview) for additional // details and options. - Model Model `json:"model,required"` + Model Model `json:"model" api:"required"` // The reason that we stopped. // // This may be one the following values: @@ -99,11 +99,11 @@ type Completion struct { // - `"stop_sequence"`: we reached a stop sequence — either provided by you via the // `stop_sequences` parameter, or a stop sequence built into the model // - `"max_tokens"`: we exceeded `max_tokens_to_sample` or the model's maximum - StopReason string `json:"stop_reason,required"` + StopReason string `json:"stop_reason" api:"required"` // Object type. // // For Text Completions, this is always `"completion"`. - Type constant.Completion `json:"type,required"` + Type constant.Completion `json:"type" api:"required"` // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. JSON struct { ID respjson.Field @@ -127,11 +127,11 @@ type CompletionNewParams struct { // // Note that our models may stop _before_ reaching this maximum. This parameter // only specifies the absolute maximum number of tokens to generate. - MaxTokensToSample int64 `json:"max_tokens_to_sample,required"` + MaxTokensToSample int64 `json:"max_tokens_to_sample" api:"required"` // The model that will complete your prompt.\n\nSee // [models](https://docs.anthropic.com/en/docs/models-overview) for additional // details and options. - Model Model `json:"model,omitzero,required"` + Model Model `json:"model,omitzero" api:"required"` // The prompt that you want Claude to complete. // // For proper response generation you will need to format your prompt using @@ -144,7 +144,7 @@ type CompletionNewParams struct { // See [prompt validation](https://docs.claude.com/en/api/prompt-validation) and // our guide to [prompt design](https://docs.claude.com/en/docs/intro-to-prompting) // for more details. - Prompt string `json:"prompt,required"` + Prompt string `json:"prompt" api:"required"` // Amount of randomness injected into the response. // // Defaults to `1.0`. Ranges from `0.0` to `1.0`. Use `temperature` closer to `0.0` diff --git a/internal/apiform/encoder.go b/internal/apiform/encoder.go index 9c29b18c..106cb125 100644 --- a/internal/apiform/encoder.go +++ b/internal/apiform/encoder.go @@ -469,5 +469,5 @@ func WriteExtras(writer *multipart.Writer, extras map[string]any) (err error) { break } } - return + return err } diff --git a/internal/apiform/form_test.go b/internal/apiform/form_test.go index 30565df0..d6df84e5 100644 --- a/internal/apiform/form_test.go +++ b/internal/apiform/form_test.go @@ -48,18 +48,18 @@ type DateTime struct { type AdditionalProperties struct { A bool `form:"a"` - Extras map[string]any `form:"-,extras"` + Extras map[string]any `form:"-" api:"extrafields"` } type TypedAdditionalProperties struct { A bool `form:"a"` - Extras map[string]int `form:"-,extras"` + Extras map[string]int `form:"-" api:"extrafields"` } type EmbeddedStructs struct { AdditionalProperties A *int `form:"number2"` - Extras map[string]any `form:"-,extras"` + Extras map[string]any `form:"-" api:"extrafields"` } type Recursive struct { @@ -585,14 +585,17 @@ func TestEncode(t *testing.T) { t.Run(name, func(t *testing.T) { buf := bytes.NewBuffer(nil) writer := multipart.NewWriter(buf) - writer.SetBoundary("xxx") + err := writer.SetBoundary("xxx") + if err != nil { + t.Errorf("setting boundary for %v failed with error %v", test.val, err) + } - var arrayFmt string = "indices:dots" + arrayFmt := "indices:dots" if tags := strings.Split(name, ","); len(tags) > 1 { arrayFmt = tags[1] } - err := MarshalWithSettings(test.val, writer, arrayFmt) + err = MarshalWithSettings(test.val, writer, arrayFmt) if err != nil { t.Errorf("serialization of %v failed with error %v", test.val, err) } diff --git a/internal/apiform/tag.go b/internal/apiform/tag.go index 736fc1ea..d9915d4a 100644 --- a/internal/apiform/tag.go +++ b/internal/apiform/tag.go @@ -5,6 +5,7 @@ import ( "strings" ) +const apiStructTag = "api" const jsonStructTag = "json" const formStructTag = "form" const formatStructTag = "format" @@ -23,7 +24,7 @@ func parseFormStructTag(field reflect.StructField) (tag parsedStructTag, ok bool raw, ok = field.Tag.Lookup(jsonStructTag) } if !ok { - return + return tag, ok } parts := strings.Split(raw, ",") if len(parts) == 0 { @@ -42,10 +43,30 @@ func parseFormStructTag(field reflect.StructField) (tag parsedStructTag, ok bool tag.omitzero = true } } - return + + parseApiStructTag(field, &tag) + return tag, ok +} + +func parseApiStructTag(field reflect.StructField, tag *parsedStructTag) { + raw, ok := field.Tag.Lookup(apiStructTag) + if !ok { + return + } + parts := strings.Split(raw, ",") + for _, part := range parts { + switch part { + case "extrafields": + tag.extras = true + case "required": + tag.required = true + case "metadata": + tag.metadata = true + } + } } func parseFormatStructTag(field reflect.StructField) (format string, ok bool) { format, ok = field.Tag.Lookup(formatStructTag) - return + return format, ok } diff --git a/internal/apijson/decodeparam_test.go b/internal/apijson/decodeparam_test.go index 1546cefc..2d6c4b05 100644 --- a/internal/apijson/decodeparam_test.go +++ b/internal/apijson/decodeparam_test.go @@ -50,10 +50,10 @@ func TestOptionalDecoders(t *testing.T) { type paramObject = param.APIObject type BasicObject struct { - ReqInt int64 `json:"req_int,required"` - ReqFloat float64 `json:"req_float,required"` - ReqString string `json:"req_string,required"` - ReqBool bool `json:"req_bool,required"` + ReqInt int64 `json:"req_int" api:"required"` + ReqFloat float64 `json:"req_float" api:"required"` + ReqString string `json:"req_string" api:"required"` + ReqBool bool `json:"req_bool" api:"required"` OptInt param.Opt[int64] `json:"opt_int"` OptFloat param.Opt[float64] `json:"opt_float"` @@ -110,7 +110,7 @@ func TestBasicObject(t *testing.T) { } type ComplexObject struct { - Basic BasicObject `json:"basic,required"` + Basic BasicObject `json:"basic" api:"required"` Enum string `json:"enum"` paramObject } @@ -152,29 +152,29 @@ func TestComplexObject(t *testing.T) { type paramUnion = param.APIUnion type MemberA struct { - Name string `json:"name,required"` - Age int `json:"age,required"` + Name string `json:"name" api:"required"` + Age int `json:"age" api:"required"` } type MemberB struct { - Name string `json:"name,required"` - Age string `json:"age,required"` + Name string `json:"name" api:"required"` + Age string `json:"age" api:"required"` } type MemberC struct { - Name string `json:"name,required"` - Age int `json:"age,required"` + Name string `json:"name" api:"required"` + Age int `json:"age" api:"required"` Status string `json:"status"` } type MemberD struct { - Cost int `json:"cost,required"` - Status string `json:"status,required"` + Cost int `json:"cost" api:"required"` + Status string `json:"status" api:"required"` } type MemberE struct { - Cost int `json:"cost,required"` - Status string `json:"status,required"` + Cost int `json:"cost" api:"required"` + Status string `json:"status" api:"required"` } type MemberF struct { @@ -318,21 +318,21 @@ func (c ConstantB) Default() string { return "B" } func (c ConstantC) Default() string { return "C" } type DiscVariantA struct { - Name string `json:"name,required"` - Age int `json:"age,required"` - Type ConstantA `json:"type,required"` + Name string `json:"name" api:"required"` + Age int `json:"age" api:"required"` + Type ConstantA `json:"type" api:"required"` } type DiscVariantB struct { - Name string `json:"name,required"` - Age int `json:"age,required"` - Type ConstantB `json:"type,required"` + Name string `json:"name" api:"required"` + Age int `json:"age" api:"required"` + Type ConstantB `json:"type" api:"required"` } type DiscVariantC struct { - Name string `json:"name,required"` - Age float64 `json:"age,required"` - Type ConstantC `json:"type,required"` + Name string `json:"name" api:"required"` + Age float64 `json:"age" api:"required"` + Type ConstantC `json:"type" api:"required"` } type DiscriminatedUnion struct { @@ -352,13 +352,13 @@ func init() { } type FooVariant struct { - Type string `json:"type,required"` - Value string `json:"value,required"` + Type string `json:"type" api:"required"` + Value string `json:"value" api:"required"` } type BarVariant struct { - Type string `json:"type,required"` - Enable bool `json:"enable,required"` + Type string `json:"type" api:"required"` + Enable bool `json:"enable" api:"required"` } type MultiDiscriminatorUnion struct { diff --git a/internal/apijson/decoder.go b/internal/apijson/decoder.go index 7c061093..26d15b24 100644 --- a/internal/apijson/decoder.go +++ b/internal/apijson/decoder.go @@ -410,7 +410,7 @@ func (d *decoderBuilder) newStructTypeDecoder(t reflect.Type) decoderFunc { for _, decoder := range anonymousDecoders { // ignore errors - decoder.fn(node, value.FieldByIndex(decoder.idx), state) + _ = decoder.fn(node, value.FieldByIndex(decoder.idx), state) } for _, inlineDecoder := range inlineDecoders { @@ -479,7 +479,7 @@ func (d *decoderBuilder) newStructTypeDecoder(t reflect.Type) decoderFunc { // Handle null [param.Opt] if itemNode.Type == gjson.Null && dest.IsValid() && dest.Type().Implements(reflect.TypeOf((*param.Optional)(nil)).Elem()) { - dest.Addr().Interface().(json.Unmarshaler).UnmarshalJSON([]byte(itemNode.Raw)) + _ = dest.Addr().Interface().(json.Unmarshaler).UnmarshalJSON([]byte(itemNode.Raw)) continue } @@ -701,8 +701,5 @@ func guardUnknown(state *decoderState, v reflect.Value) bool { constantString, ok := v.Interface().(interface{ Default() string }) named := v.Type() != stringType - if guardStrict(state, ok && named && v.Equal(reflect.ValueOf(constantString.Default()))) { - return true - } - return false + return guardStrict(state, ok && named && v.Equal(reflect.ValueOf(constantString.Default()))) } diff --git a/internal/apijson/decoderesp_test.go b/internal/apijson/decoderesp_test.go index 551dac83..ff1f1edc 100644 --- a/internal/apijson/decoderesp_test.go +++ b/internal/apijson/decoderesp_test.go @@ -8,7 +8,7 @@ import ( ) type StructWithNullExtraField struct { - Results []string `json:"results,required"` + Results []string `json:"results" api:"required"` JSON struct { Results respjson.Field ExtraFields map[string]respjson.Field diff --git a/internal/apijson/encoder.go b/internal/apijson/encoder.go index ab7a3c15..0decb733 100644 --- a/internal/apijson/encoder.go +++ b/internal/apijson/encoder.go @@ -286,28 +286,7 @@ func (e *encoder) newStructTypeEncoder(t reflect.Type) encoderFunc { return nil, err } } - return - } -} - -func (e *encoder) newFieldTypeEncoder(t reflect.Type) encoderFunc { - f, _ := t.FieldByName("Value") - enc := e.typeEncoder(f.Type) - - return func(value reflect.Value) (json []byte, err error) { - present := value.FieldByName("Present") - if !present.Bool() { - return nil, nil - } - null := value.FieldByName("Null") - if null.Bool() { - return []byte("null"), nil - } - raw := value.FieldByName("Raw") - if !raw.IsNil() { - return e.typeEncoder(raw.Type())(raw) - } - return enc(value.FieldByName("Value")) + return json, err } } diff --git a/internal/apijson/enum.go b/internal/apijson/enum.go index 5bef11c3..a1626a57 100644 --- a/internal/apijson/enum.go +++ b/internal/apijson/enum.go @@ -4,7 +4,6 @@ import ( "fmt" "reflect" "slices" - "sync" "github.com/tidwall/gjson" ) @@ -15,7 +14,6 @@ import ( type validationEntry struct { field reflect.StructField - required bool legalValues struct { strings []string // 1 represents true, 0 represents false, -1 represents either @@ -24,9 +22,6 @@ type validationEntry struct { } } -type validatorFunc func(reflect.Value) exactness - -var validators sync.Map var validationRegistry = map[reflect.Type][]validationEntry{} func RegisterFieldValidator[T any, V string | bool | int | float64](fieldName string, values ...V) { @@ -111,9 +106,9 @@ func (state *decoderState) validateBool(v reflect.Value) { return } b := v.Bool() - if state.validator.legalValues.bools == 1 && b == false { + if state.validator.legalValues.bools == 1 && !b { state.exactness = loose - } else if state.validator.legalValues.bools == 0 && b == true { + } else if state.validator.legalValues.bools == 0 && b { state.exactness = loose } } diff --git a/internal/apijson/json_test.go b/internal/apijson/json_test.go index 02904d27..19b36146 100644 --- a/internal/apijson/json_test.go +++ b/internal/apijson/json_test.go @@ -40,12 +40,12 @@ type DateTime struct { type AdditionalProperties struct { A bool `json:"a"` - ExtraFields map[string]any `json:"-,extras"` + ExtraFields map[string]any `json:"-" api:"extrafields"` } type TypedAdditionalProperties struct { A bool `json:"a"` - ExtraFields map[string]int `json:"-,extras"` + ExtraFields map[string]int `json:"-" api:"extrafields"` } type EmbeddedStruct struct { @@ -65,7 +65,7 @@ type EmbeddedStructJSON struct { type EmbeddedStructs struct { EmbeddedStruct A *int `json:"a"` - ExtraFields map[string]any `json:"-,extras"` + ExtraFields map[string]any `json:"-" api:"extrafields"` JSON EmbeddedStructsJSON } @@ -86,8 +86,8 @@ type JSONFieldStruct struct { B int64 `json:"b"` C string `json:"c"` D string `json:"d"` - ExtraFields map[string]int64 `json:",extras"` - JSON JSONFieldStructJSON `json:",metadata"` + ExtraFields map[string]int64 `json:"" api:"extrafields"` + JSON JSONFieldStructJSON `json:"-" api:"metadata"` } type JSONFieldStructJSON struct { @@ -113,12 +113,12 @@ type Union interface { type Inline struct { InlineField Primitives `json:",inline"` - JSON InlineJSON `json:",metadata"` + JSON InlineJSON `json:"-" api:"metadata"` } type InlineArray struct { InlineField []string `json:",inline"` - JSON InlineJSON `json:",metadata"` + JSON InlineJSON `json:"-" api:"metadata"` } type InlineJSON struct { @@ -268,7 +268,7 @@ type MarshallingUnionStruct struct { func (r *MarshallingUnionStruct) UnmarshalJSON(data []byte) (err error) { *r = MarshallingUnionStruct{} err = UnmarshalRoot(data, &r.Union) - return + return err } func (r MarshallingUnionStruct) MarshalJSON() (data []byte, err error) { diff --git a/internal/apijson/tag.go b/internal/apijson/tag.go index 812fb3ca..17b21302 100644 --- a/internal/apijson/tag.go +++ b/internal/apijson/tag.go @@ -5,6 +5,7 @@ import ( "strings" ) +const apiStructTag = "api" const jsonStructTag = "json" const formatStructTag = "format" @@ -19,7 +20,7 @@ type parsedStructTag struct { func parseJSONStructTag(field reflect.StructField) (tag parsedStructTag, ok bool) { raw, ok := field.Tag.Lookup(jsonStructTag) if !ok { - return + return tag, ok } parts := strings.Split(raw, ",") if len(parts) == 0 { @@ -38,10 +39,31 @@ func parseJSONStructTag(field reflect.StructField) (tag parsedStructTag, ok bool tag.inline = true } } - return + + // the `api` struct tag is only used alongside `json` for custom behaviour + parseApiStructTag(field, &tag) + return tag, ok +} + +func parseApiStructTag(field reflect.StructField, tag *parsedStructTag) { + raw, ok := field.Tag.Lookup(apiStructTag) + if !ok { + return + } + parts := strings.Split(raw, ",") + for _, part := range parts { + switch part { + case "extrafields": + tag.extras = true + case "required": + tag.required = true + case "metadata": + tag.metadata = true + } + } } func parseFormatStructTag(field reflect.StructField) (format string, ok bool) { format, ok = field.Tag.Lookup(formatStructTag) - return + return format, ok } diff --git a/internal/apiquery/encoder.go b/internal/apiquery/encoder.go index 08641cdf..d0437907 100644 --- a/internal/apiquery/encoder.go +++ b/internal/apiquery/encoder.go @@ -103,7 +103,7 @@ func (e *encoder) newTypeEncoder(t reflect.Type) encoderFunc { encoder := e.typeEncoder(t.Elem()) return func(key string, value reflect.Value) (pairs []Pair, err error) { if !value.IsValid() || value.IsNil() { - return + return pairs, err } return encoder(key, value.Elem()) } @@ -193,7 +193,7 @@ func (e *encoder) newStructTypeEncoder(t reflect.Type) encoderFunc { return func(key string, value reflect.Value) (pairs []Pair, err error) { for _, ef := range encoderFields { - var subkey string = e.renderKeyPath(key, ef.tag.name) + subkey := e.renderKeyPath(key, ef.tag.name) if ef.tag.inline { subkey = key } @@ -205,7 +205,7 @@ func (e *encoder) newStructTypeEncoder(t reflect.Type) encoderFunc { } pairs = append(pairs, subpairs...) } - return + return pairs, err } } @@ -256,7 +256,7 @@ func (e *encoder) newMapEncoder(t reflect.Type) encoderFunc { } pairs = append(pairs, subpairs...) } - return + return pairs, err } } @@ -300,7 +300,7 @@ func (e *encoder) newArrayTypeEncoder(t reflect.Type) encoderFunc { } pairs = append(pairs, subpairs...) } - return + return pairs, err } case ArrayQueryFormatIndices: panic("The array indices format is not supported yet") @@ -315,7 +315,7 @@ func (e *encoder) newArrayTypeEncoder(t reflect.Type) encoderFunc { } pairs = append(pairs, subpairs...) } - return + return pairs, err } default: panic(fmt.Sprintf("Unknown ArrayFormat value: %d", e.settings.ArrayFormat)) @@ -372,27 +372,6 @@ func (e *encoder) newPrimitiveTypeEncoder(t reflect.Type) encoderFunc { } } -func (e *encoder) newFieldTypeEncoder(t reflect.Type) encoderFunc { - f, _ := t.FieldByName("Value") - enc := e.typeEncoder(f.Type) - - return func(key string, value reflect.Value) ([]Pair, error) { - present := value.FieldByName("Present") - if !present.Bool() { - return nil, nil - } - null := value.FieldByName("Null") - if null.Bool() { - return nil, fmt.Errorf("apiquery: field cannot be null") - } - raw := value.FieldByName("Raw") - if !raw.IsNil() { - return e.typeEncoder(raw.Type())(key, raw) - } - return enc(key, value.FieldByName("Value")) - } -} - func (e *encoder) newTimeTypeEncoder(_ reflect.Type) encoderFunc { format := e.dateFormat return func(key string, value reflect.Value) ([]Pair, error) { diff --git a/internal/apiquery/tag.go b/internal/apiquery/tag.go index 772c40e1..9e413ad8 100644 --- a/internal/apiquery/tag.go +++ b/internal/apiquery/tag.go @@ -18,7 +18,7 @@ type parsedStructTag struct { func parseQueryStructTag(field reflect.StructField) (tag parsedStructTag, ok bool) { raw, ok := field.Tag.Lookup(queryStructTag) if !ok { - return + return tag, ok } parts := strings.Split(raw, ",") if len(parts) == 0 { @@ -35,10 +35,10 @@ func parseQueryStructTag(field reflect.StructField) (tag parsedStructTag, ok boo tag.inline = true } } - return + return tag, ok } func parseFormatStructTag(field reflect.StructField) (format string, ok bool) { format, ok = field.Tag.Lookup(formatStructTag) - return + return format, ok } diff --git a/internal/requestconfig/requestconfig.go b/internal/requestconfig/requestconfig.go index 42cfa4d5..b4b0d308 100644 --- a/internal/requestconfig/requestconfig.go +++ b/internal/requestconfig/requestconfig.go @@ -356,11 +356,9 @@ func (b *bodyWithTimeout) Close() error { } func retryDelay(res *http.Response, retryCount int) time.Duration { - // If the API asks us to wait a certain amount of time (and it's a reasonable amount), - // just do what it says. - - if retryAfterDelay, ok := parseRetryAfterHeader(res); ok && 0 <= retryAfterDelay && retryAfterDelay < time.Minute { - return retryAfterDelay + // If the backend tells us to wait a certain amount of time, use that value + if retryAfterDelay, ok := parseRetryAfterHeader(res); ok { + return max(0, retryAfterDelay) } maxDelay := 8 * time.Second @@ -464,10 +462,14 @@ func (cfg *RequestConfig) Execute() (err error) { // Close the response body before retrying to prevent connection leaks if res != nil && res.Body != nil { - res.Body.Close() + _ = res.Body.Close() } - time.Sleep(retryDelay(res, retryCount)) + select { + case <-ctx.Done(): + return ctx.Err() + case <-time.After(retryDelay(res, retryCount)): + } } // Save *http.Response if it is requested to, even if there was an error making the request. This is @@ -488,7 +490,7 @@ func (cfg *RequestConfig) Execute() (err error) { if res.StatusCode >= 400 { contents, err := io.ReadAll(res.Body) - res.Body.Close() + _ = res.Body.Close() if err != nil { return err } @@ -519,7 +521,7 @@ func (cfg *RequestConfig) Execute() (err error) { } contents, err := io.ReadAll(res.Body) - res.Body.Close() + _ = res.Body.Close() if err != nil { return fmt.Errorf("error reading response body: %w", err) } diff --git a/internal/version.go b/internal/version.go index abcd6772..915d8022 100644 --- a/internal/version.go +++ b/internal/version.go @@ -2,4 +2,4 @@ package internal -const PackageVersion = "1.26.0" // x-release-please-version +const PackageVersion = "1.27.0" // x-release-please-version diff --git a/message.go b/message.go index 052dc114..182e22e1 100644 --- a/message.go +++ b/message.go @@ -65,7 +65,7 @@ func (r *MessageService) New(ctx context.Context, body MessageNewParams, opts .. path := "v1/messages" err = requestconfig.ExecuteNewRequest(ctx, http.MethodPost, path, body, &res, opts...) - return + return res, err } // Send a structured list of input messages with text and/or image content, and the @@ -101,16 +101,16 @@ func (r *MessageService) CountTokens(ctx context.Context, body MessageCountToken opts = slices.Concat(r.Options, opts) path := "v1/messages/count_tokens" err = requestconfig.ExecuteNewRequest(ctx, http.MethodPost, path, body, &res, opts...) - return + return res, err } // The properties Data, MediaType, Type are required. type Base64ImageSourceParam struct { - Data string `json:"data,required" format:"byte"` + Data string `json:"data" api:"required" format:"byte"` // Any of "image/jpeg", "image/png", "image/gif", "image/webp". - MediaType Base64ImageSourceMediaType `json:"media_type,omitzero,required"` + MediaType Base64ImageSourceMediaType `json:"media_type,omitzero" api:"required"` // This field can be elided, and will marshal its zero value as "base64". - Type constant.Base64 `json:"type,required"` + Type constant.Base64 `json:"type" api:"required"` paramObj } @@ -132,9 +132,9 @@ const ( ) type Base64PDFSource struct { - Data string `json:"data,required" format:"byte"` - MediaType constant.ApplicationPDF `json:"media_type,required"` - Type constant.Base64 `json:"type,required"` + Data string `json:"data" api:"required" format:"byte"` + MediaType constant.ApplicationPDF `json:"media_type" api:"required"` + Type constant.Base64 `json:"type" api:"required"` // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. JSON struct { Data respjson.Field @@ -162,11 +162,11 @@ func (r Base64PDFSource) ToParam() Base64PDFSourceParam { // The properties Data, MediaType, Type are required. type Base64PDFSourceParam struct { - Data string `json:"data,required" format:"byte"` + Data string `json:"data" api:"required" format:"byte"` // This field can be elided, and will marshal its zero value as "application/pdf". - MediaType constant.ApplicationPDF `json:"media_type,required"` + MediaType constant.ApplicationPDF `json:"media_type" api:"required"` // This field can be elided, and will marshal its zero value as "base64". - Type constant.Base64 `json:"type,required"` + Type constant.Base64 `json:"type" api:"required"` paramObj } @@ -179,8 +179,8 @@ func (r *Base64PDFSourceParam) UnmarshalJSON(data []byte) error { } type BashCodeExecutionOutputBlock struct { - FileID string `json:"file_id,required"` - Type constant.BashCodeExecutionOutput `json:"type,required"` + FileID string `json:"file_id" api:"required"` + Type constant.BashCodeExecutionOutput `json:"type" api:"required"` // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. JSON struct { FileID respjson.Field @@ -198,10 +198,10 @@ func (r *BashCodeExecutionOutputBlock) UnmarshalJSON(data []byte) error { // The properties FileID, Type are required. type BashCodeExecutionOutputBlockParam struct { - FileID string `json:"file_id,required"` + FileID string `json:"file_id" api:"required"` // This field can be elided, and will marshal its zero value as // "bash_code_execution_output". - Type constant.BashCodeExecutionOutput `json:"type,required"` + Type constant.BashCodeExecutionOutput `json:"type" api:"required"` paramObj } @@ -214,11 +214,11 @@ func (r *BashCodeExecutionOutputBlockParam) UnmarshalJSON(data []byte) error { } type BashCodeExecutionResultBlock struct { - Content []BashCodeExecutionOutputBlock `json:"content,required"` - ReturnCode int64 `json:"return_code,required"` - Stderr string `json:"stderr,required"` - Stdout string `json:"stdout,required"` - Type constant.BashCodeExecutionResult `json:"type,required"` + Content []BashCodeExecutionOutputBlock `json:"content" api:"required"` + ReturnCode int64 `json:"return_code" api:"required"` + Stderr string `json:"stderr" api:"required"` + Stdout string `json:"stdout" api:"required"` + Type constant.BashCodeExecutionResult `json:"type" api:"required"` // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. JSON struct { Content respjson.Field @@ -239,13 +239,13 @@ func (r *BashCodeExecutionResultBlock) UnmarshalJSON(data []byte) error { // The properties Content, ReturnCode, Stderr, Stdout, Type are required. type BashCodeExecutionResultBlockParam struct { - Content []BashCodeExecutionOutputBlockParam `json:"content,omitzero,required"` - ReturnCode int64 `json:"return_code,required"` - Stderr string `json:"stderr,required"` - Stdout string `json:"stdout,required"` + Content []BashCodeExecutionOutputBlockParam `json:"content,omitzero" api:"required"` + ReturnCode int64 `json:"return_code" api:"required"` + Stderr string `json:"stderr" api:"required"` + Stdout string `json:"stdout" api:"required"` // This field can be elided, and will marshal its zero value as // "bash_code_execution_result". - Type constant.BashCodeExecutionResult `json:"type,required"` + Type constant.BashCodeExecutionResult `json:"type" api:"required"` paramObj } @@ -258,9 +258,9 @@ func (r *BashCodeExecutionResultBlockParam) UnmarshalJSON(data []byte) error { } type BashCodeExecutionToolResultBlock struct { - Content BashCodeExecutionToolResultBlockContentUnion `json:"content,required"` - ToolUseID string `json:"tool_use_id,required"` - Type constant.BashCodeExecutionToolResult `json:"type,required"` + Content BashCodeExecutionToolResultBlockContentUnion `json:"content" api:"required"` + ToolUseID string `json:"tool_use_id" api:"required"` + Type constant.BashCodeExecutionToolResult `json:"type" api:"required"` // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. JSON struct { Content respjson.Field @@ -324,13 +324,13 @@ func (r *BashCodeExecutionToolResultBlockContentUnion) UnmarshalJSON(data []byte // The properties Content, ToolUseID, Type are required. type BashCodeExecutionToolResultBlockParam struct { - Content BashCodeExecutionToolResultBlockParamContentUnion `json:"content,omitzero,required"` - ToolUseID string `json:"tool_use_id,required"` + Content BashCodeExecutionToolResultBlockParamContentUnion `json:"content,omitzero" api:"required"` + ToolUseID string `json:"tool_use_id" api:"required"` // Create a cache control breakpoint at this content block. CacheControl CacheControlEphemeralParam `json:"cache_control,omitzero"` // This field can be elided, and will marshal its zero value as // "bash_code_execution_tool_result". - Type constant.BashCodeExecutionToolResult `json:"type,required"` + Type constant.BashCodeExecutionToolResult `json:"type" api:"required"` paramObj } @@ -420,8 +420,8 @@ func (u BashCodeExecutionToolResultBlockParamContentUnion) GetType() *string { type BashCodeExecutionToolResultError struct { // Any of "invalid_tool_input", "unavailable", "too_many_requests", // "execution_time_exceeded", "output_file_too_large". - ErrorCode BashCodeExecutionToolResultErrorCode `json:"error_code,required"` - Type constant.BashCodeExecutionToolResultError `json:"type,required"` + ErrorCode BashCodeExecutionToolResultErrorCode `json:"error_code" api:"required"` + Type constant.BashCodeExecutionToolResultError `json:"type" api:"required"` // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. JSON struct { ErrorCode respjson.Field @@ -451,10 +451,10 @@ const ( type BashCodeExecutionToolResultErrorParam struct { // Any of "invalid_tool_input", "unavailable", "too_many_requests", // "execution_time_exceeded", "output_file_too_large". - ErrorCode BashCodeExecutionToolResultErrorCode `json:"error_code,omitzero,required"` + ErrorCode BashCodeExecutionToolResultErrorCode `json:"error_code,omitzero" api:"required"` // This field can be elided, and will marshal its zero value as // "bash_code_execution_tool_result_error". - Type constant.BashCodeExecutionToolResultError `json:"type,required"` + Type constant.BashCodeExecutionToolResultError `json:"type" api:"required"` paramObj } @@ -486,7 +486,7 @@ type CacheControlEphemeralParam struct { // // Any of "5m", "1h". TTL CacheControlEphemeralTTL `json:"ttl,omitzero"` - Type constant.Ephemeral `json:"type,required"` + Type constant.Ephemeral `json:"type" api:"required"` paramObj } @@ -515,9 +515,9 @@ const ( type CacheCreation struct { // The number of input tokens used to create the 1 hour cache entry. - Ephemeral1hInputTokens int64 `json:"ephemeral_1h_input_tokens,required"` + Ephemeral1hInputTokens int64 `json:"ephemeral_1h_input_tokens" api:"required"` // The number of input tokens used to create the 5 minute cache entry. - Ephemeral5mInputTokens int64 `json:"ephemeral_5m_input_tokens,required"` + Ephemeral5mInputTokens int64 `json:"ephemeral_5m_input_tokens" api:"required"` // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. JSON struct { Ephemeral1hInputTokens respjson.Field @@ -534,13 +534,13 @@ func (r *CacheCreation) UnmarshalJSON(data []byte) error { } type CitationCharLocation struct { - CitedText string `json:"cited_text,required"` - DocumentIndex int64 `json:"document_index,required"` - DocumentTitle string `json:"document_title,required"` - EndCharIndex int64 `json:"end_char_index,required"` - FileID string `json:"file_id,required"` - StartCharIndex int64 `json:"start_char_index,required"` - Type constant.CharLocation `json:"type,required"` + CitedText string `json:"cited_text" api:"required"` + DocumentIndex int64 `json:"document_index" api:"required"` + DocumentTitle string `json:"document_title" api:"required"` + EndCharIndex int64 `json:"end_char_index" api:"required"` + FileID string `json:"file_id" api:"required"` + StartCharIndex int64 `json:"start_char_index" api:"required"` + Type constant.CharLocation `json:"type" api:"required"` // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. JSON struct { CitedText respjson.Field @@ -564,13 +564,13 @@ func (r *CitationCharLocation) UnmarshalJSON(data []byte) error { // The properties CitedText, DocumentIndex, DocumentTitle, EndCharIndex, // StartCharIndex, Type are required. type CitationCharLocationParam struct { - DocumentTitle param.Opt[string] `json:"document_title,omitzero,required"` - CitedText string `json:"cited_text,required"` - DocumentIndex int64 `json:"document_index,required"` - EndCharIndex int64 `json:"end_char_index,required"` - StartCharIndex int64 `json:"start_char_index,required"` + DocumentTitle param.Opt[string] `json:"document_title,omitzero" api:"required"` + CitedText string `json:"cited_text" api:"required"` + DocumentIndex int64 `json:"document_index" api:"required"` + EndCharIndex int64 `json:"end_char_index" api:"required"` + StartCharIndex int64 `json:"start_char_index" api:"required"` // This field can be elided, and will marshal its zero value as "char_location". - Type constant.CharLocation `json:"type,required"` + Type constant.CharLocation `json:"type" api:"required"` paramObj } @@ -583,13 +583,13 @@ func (r *CitationCharLocationParam) UnmarshalJSON(data []byte) error { } type CitationContentBlockLocation struct { - CitedText string `json:"cited_text,required"` - DocumentIndex int64 `json:"document_index,required"` - DocumentTitle string `json:"document_title,required"` - EndBlockIndex int64 `json:"end_block_index,required"` - FileID string `json:"file_id,required"` - StartBlockIndex int64 `json:"start_block_index,required"` - Type constant.ContentBlockLocation `json:"type,required"` + CitedText string `json:"cited_text" api:"required"` + DocumentIndex int64 `json:"document_index" api:"required"` + DocumentTitle string `json:"document_title" api:"required"` + EndBlockIndex int64 `json:"end_block_index" api:"required"` + FileID string `json:"file_id" api:"required"` + StartBlockIndex int64 `json:"start_block_index" api:"required"` + Type constant.ContentBlockLocation `json:"type" api:"required"` // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. JSON struct { CitedText respjson.Field @@ -613,14 +613,14 @@ func (r *CitationContentBlockLocation) UnmarshalJSON(data []byte) error { // The properties CitedText, DocumentIndex, DocumentTitle, EndBlockIndex, // StartBlockIndex, Type are required. type CitationContentBlockLocationParam struct { - DocumentTitle param.Opt[string] `json:"document_title,omitzero,required"` - CitedText string `json:"cited_text,required"` - DocumentIndex int64 `json:"document_index,required"` - EndBlockIndex int64 `json:"end_block_index,required"` - StartBlockIndex int64 `json:"start_block_index,required"` + DocumentTitle param.Opt[string] `json:"document_title,omitzero" api:"required"` + CitedText string `json:"cited_text" api:"required"` + DocumentIndex int64 `json:"document_index" api:"required"` + EndBlockIndex int64 `json:"end_block_index" api:"required"` + StartBlockIndex int64 `json:"start_block_index" api:"required"` // This field can be elided, and will marshal its zero value as // "content_block_location". - Type constant.ContentBlockLocation `json:"type,required"` + Type constant.ContentBlockLocation `json:"type" api:"required"` paramObj } @@ -633,13 +633,13 @@ func (r *CitationContentBlockLocationParam) UnmarshalJSON(data []byte) error { } type CitationPageLocation struct { - CitedText string `json:"cited_text,required"` - DocumentIndex int64 `json:"document_index,required"` - DocumentTitle string `json:"document_title,required"` - EndPageNumber int64 `json:"end_page_number,required"` - FileID string `json:"file_id,required"` - StartPageNumber int64 `json:"start_page_number,required"` - Type constant.PageLocation `json:"type,required"` + CitedText string `json:"cited_text" api:"required"` + DocumentIndex int64 `json:"document_index" api:"required"` + DocumentTitle string `json:"document_title" api:"required"` + EndPageNumber int64 `json:"end_page_number" api:"required"` + FileID string `json:"file_id" api:"required"` + StartPageNumber int64 `json:"start_page_number" api:"required"` + Type constant.PageLocation `json:"type" api:"required"` // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. JSON struct { CitedText respjson.Field @@ -663,13 +663,13 @@ func (r *CitationPageLocation) UnmarshalJSON(data []byte) error { // The properties CitedText, DocumentIndex, DocumentTitle, EndPageNumber, // StartPageNumber, Type are required. type CitationPageLocationParam struct { - DocumentTitle param.Opt[string] `json:"document_title,omitzero,required"` - CitedText string `json:"cited_text,required"` - DocumentIndex int64 `json:"document_index,required"` - EndPageNumber int64 `json:"end_page_number,required"` - StartPageNumber int64 `json:"start_page_number,required"` + DocumentTitle param.Opt[string] `json:"document_title,omitzero" api:"required"` + CitedText string `json:"cited_text" api:"required"` + DocumentIndex int64 `json:"document_index" api:"required"` + EndPageNumber int64 `json:"end_page_number" api:"required"` + StartPageNumber int64 `json:"start_page_number" api:"required"` // This field can be elided, and will marshal its zero value as "page_location". - Type constant.PageLocation `json:"type,required"` + Type constant.PageLocation `json:"type" api:"required"` paramObj } @@ -684,15 +684,15 @@ func (r *CitationPageLocationParam) UnmarshalJSON(data []byte) error { // The properties CitedText, EndBlockIndex, SearchResultIndex, Source, // StartBlockIndex, Title, Type are required. type CitationSearchResultLocationParam struct { - Title param.Opt[string] `json:"title,omitzero,required"` - CitedText string `json:"cited_text,required"` - EndBlockIndex int64 `json:"end_block_index,required"` - SearchResultIndex int64 `json:"search_result_index,required"` - Source string `json:"source,required"` - StartBlockIndex int64 `json:"start_block_index,required"` + Title param.Opt[string] `json:"title,omitzero" api:"required"` + CitedText string `json:"cited_text" api:"required"` + EndBlockIndex int64 `json:"end_block_index" api:"required"` + SearchResultIndex int64 `json:"search_result_index" api:"required"` + Source string `json:"source" api:"required"` + StartBlockIndex int64 `json:"start_block_index" api:"required"` // This field can be elided, and will marshal its zero value as // "search_result_location". - Type constant.SearchResultLocation `json:"type,required"` + Type constant.SearchResultLocation `json:"type" api:"required"` paramObj } @@ -706,13 +706,13 @@ func (r *CitationSearchResultLocationParam) UnmarshalJSON(data []byte) error { // The properties CitedText, EncryptedIndex, Title, Type, URL are required. type CitationWebSearchResultLocationParam struct { - Title param.Opt[string] `json:"title,omitzero,required"` - CitedText string `json:"cited_text,required"` - EncryptedIndex string `json:"encrypted_index,required"` - URL string `json:"url,required"` + Title param.Opt[string] `json:"title,omitzero" api:"required"` + CitedText string `json:"cited_text" api:"required"` + EncryptedIndex string `json:"encrypted_index" api:"required"` + URL string `json:"url" api:"required"` // This field can be elided, and will marshal its zero value as // "web_search_result_location". - Type constant.WebSearchResultLocation `json:"type,required"` + Type constant.WebSearchResultLocation `json:"type" api:"required"` paramObj } @@ -725,7 +725,7 @@ func (r *CitationWebSearchResultLocationParam) UnmarshalJSON(data []byte) error } type CitationsConfig struct { - Enabled bool `json:"enabled,required"` + Enabled bool `json:"enabled" api:"required"` // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. JSON struct { Enabled respjson.Field @@ -754,8 +754,8 @@ func (r *CitationsConfigParam) UnmarshalJSON(data []byte) error { } type CitationsDelta struct { - Citation CitationsDeltaCitationUnion `json:"citation,required"` - Type constant.CitationsDelta `json:"type,required"` + Citation CitationsDeltaCitationUnion `json:"citation" api:"required"` + Type constant.CitationsDelta `json:"type" api:"required"` // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. JSON struct { Citation respjson.Field @@ -899,13 +899,13 @@ func (r *CitationsDeltaCitationUnion) UnmarshalJSON(data []byte) error { } type CitationsSearchResultLocation struct { - CitedText string `json:"cited_text,required"` - EndBlockIndex int64 `json:"end_block_index,required"` - SearchResultIndex int64 `json:"search_result_index,required"` - Source string `json:"source,required"` - StartBlockIndex int64 `json:"start_block_index,required"` - Title string `json:"title,required"` - Type constant.SearchResultLocation `json:"type,required"` + CitedText string `json:"cited_text" api:"required"` + EndBlockIndex int64 `json:"end_block_index" api:"required"` + SearchResultIndex int64 `json:"search_result_index" api:"required"` + Source string `json:"source" api:"required"` + StartBlockIndex int64 `json:"start_block_index" api:"required"` + Title string `json:"title" api:"required"` + Type constant.SearchResultLocation `json:"type" api:"required"` // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. JSON struct { CitedText respjson.Field @@ -927,11 +927,11 @@ func (r *CitationsSearchResultLocation) UnmarshalJSON(data []byte) error { } type CitationsWebSearchResultLocation struct { - CitedText string `json:"cited_text,required"` - EncryptedIndex string `json:"encrypted_index,required"` - Title string `json:"title,required"` - Type constant.WebSearchResultLocation `json:"type,required"` - URL string `json:"url,required"` + CitedText string `json:"cited_text" api:"required"` + EncryptedIndex string `json:"encrypted_index" api:"required"` + Title string `json:"title" api:"required"` + Type constant.WebSearchResultLocation `json:"type" api:"required"` + URL string `json:"url" api:"required"` // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. JSON struct { CitedText respjson.Field @@ -951,8 +951,8 @@ func (r *CitationsWebSearchResultLocation) UnmarshalJSON(data []byte) error { } type CodeExecutionOutputBlock struct { - FileID string `json:"file_id,required"` - Type constant.CodeExecutionOutput `json:"type,required"` + FileID string `json:"file_id" api:"required"` + Type constant.CodeExecutionOutput `json:"type" api:"required"` // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. JSON struct { FileID respjson.Field @@ -970,10 +970,10 @@ func (r *CodeExecutionOutputBlock) UnmarshalJSON(data []byte) error { // The properties FileID, Type are required. type CodeExecutionOutputBlockParam struct { - FileID string `json:"file_id,required"` + FileID string `json:"file_id" api:"required"` // This field can be elided, and will marshal its zero value as // "code_execution_output". - Type constant.CodeExecutionOutput `json:"type,required"` + Type constant.CodeExecutionOutput `json:"type" api:"required"` paramObj } @@ -986,11 +986,11 @@ func (r *CodeExecutionOutputBlockParam) UnmarshalJSON(data []byte) error { } type CodeExecutionResultBlock struct { - Content []CodeExecutionOutputBlock `json:"content,required"` - ReturnCode int64 `json:"return_code,required"` - Stderr string `json:"stderr,required"` - Stdout string `json:"stdout,required"` - Type constant.CodeExecutionResult `json:"type,required"` + Content []CodeExecutionOutputBlock `json:"content" api:"required"` + ReturnCode int64 `json:"return_code" api:"required"` + Stderr string `json:"stderr" api:"required"` + Stdout string `json:"stdout" api:"required"` + Type constant.CodeExecutionResult `json:"type" api:"required"` // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. JSON struct { Content respjson.Field @@ -1011,13 +1011,13 @@ func (r *CodeExecutionResultBlock) UnmarshalJSON(data []byte) error { // The properties Content, ReturnCode, Stderr, Stdout, Type are required. type CodeExecutionResultBlockParam struct { - Content []CodeExecutionOutputBlockParam `json:"content,omitzero,required"` - ReturnCode int64 `json:"return_code,required"` - Stderr string `json:"stderr,required"` - Stdout string `json:"stdout,required"` + Content []CodeExecutionOutputBlockParam `json:"content,omitzero" api:"required"` + ReturnCode int64 `json:"return_code" api:"required"` + Stderr string `json:"stderr" api:"required"` + Stdout string `json:"stdout" api:"required"` // This field can be elided, and will marshal its zero value as // "code_execution_result". - Type constant.CodeExecutionResult `json:"type,required"` + Type constant.CodeExecutionResult `json:"type" api:"required"` paramObj } @@ -1045,10 +1045,10 @@ type CodeExecutionTool20250522Param struct { // This is how the tool will be called by the model and in `tool_use` blocks. // // This field can be elided, and will marshal its zero value as "code_execution". - Name constant.CodeExecution `json:"name,required"` + Name constant.CodeExecution `json:"name" api:"required"` // This field can be elided, and will marshal its zero value as // "code_execution_20250522". - Type constant.CodeExecution20250522 `json:"type,required"` + Type constant.CodeExecution20250522 `json:"type" api:"required"` paramObj } @@ -1076,10 +1076,10 @@ type CodeExecutionTool20250825Param struct { // This is how the tool will be called by the model and in `tool_use` blocks. // // This field can be elided, and will marshal its zero value as "code_execution". - Name constant.CodeExecution `json:"name,required"` + Name constant.CodeExecution `json:"name" api:"required"` // This field can be elided, and will marshal its zero value as // "code_execution_20250825". - Type constant.CodeExecution20250825 `json:"type,required"` + Type constant.CodeExecution20250825 `json:"type" api:"required"` paramObj } @@ -1110,10 +1110,10 @@ type CodeExecutionTool20260120Param struct { // This is how the tool will be called by the model and in `tool_use` blocks. // // This field can be elided, and will marshal its zero value as "code_execution". - Name constant.CodeExecution `json:"name,required"` + Name constant.CodeExecution `json:"name" api:"required"` // This field can be elided, and will marshal its zero value as // "code_execution_20260120". - Type constant.CodeExecution20260120 `json:"type,required"` + Type constant.CodeExecution20260120 `json:"type" api:"required"` paramObj } @@ -1127,9 +1127,9 @@ func (r *CodeExecutionTool20260120Param) UnmarshalJSON(data []byte) error { type CodeExecutionToolResultBlock struct { // Code execution result with encrypted stdout for PFC + web_search results. - Content CodeExecutionToolResultBlockContentUnion `json:"content,required"` - ToolUseID string `json:"tool_use_id,required"` - Type constant.CodeExecutionToolResult `json:"type,required"` + Content CodeExecutionToolResultBlockContentUnion `json:"content" api:"required"` + ToolUseID string `json:"tool_use_id" api:"required"` + Type constant.CodeExecutionToolResult `json:"type" api:"required"` // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. JSON struct { Content respjson.Field @@ -1199,13 +1199,13 @@ func (r *CodeExecutionToolResultBlockContentUnion) UnmarshalJSON(data []byte) er // The properties Content, ToolUseID, Type are required. type CodeExecutionToolResultBlockParam struct { // Code execution result with encrypted stdout for PFC + web_search results. - Content CodeExecutionToolResultBlockParamContentUnion `json:"content,omitzero,required"` - ToolUseID string `json:"tool_use_id,required"` + Content CodeExecutionToolResultBlockParamContentUnion `json:"content,omitzero" api:"required"` + ToolUseID string `json:"tool_use_id" api:"required"` // Create a cache control breakpoint at this content block. CacheControl CacheControlEphemeralParam `json:"cache_control,omitzero"` // This field can be elided, and will marshal its zero value as // "code_execution_tool_result". - Type constant.CodeExecutionToolResult `json:"type,required"` + Type constant.CodeExecutionToolResult `json:"type" api:"required"` paramObj } @@ -1320,8 +1320,8 @@ func (u CodeExecutionToolResultBlockParamContentUnion) GetContent() []CodeExecut type CodeExecutionToolResultError struct { // Any of "invalid_tool_input", "unavailable", "too_many_requests", // "execution_time_exceeded". - ErrorCode CodeExecutionToolResultErrorCode `json:"error_code,required"` - Type constant.CodeExecutionToolResultError `json:"type,required"` + ErrorCode CodeExecutionToolResultErrorCode `json:"error_code" api:"required"` + Type constant.CodeExecutionToolResultError `json:"type" api:"required"` // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. JSON struct { ErrorCode respjson.Field @@ -1350,10 +1350,10 @@ const ( type CodeExecutionToolResultErrorParam struct { // Any of "invalid_tool_input", "unavailable", "too_many_requests", // "execution_time_exceeded". - ErrorCode CodeExecutionToolResultErrorCode `json:"error_code,omitzero,required"` + ErrorCode CodeExecutionToolResultErrorCode `json:"error_code,omitzero" api:"required"` // This field can be elided, and will marshal its zero value as // "code_execution_tool_result_error". - Type constant.CodeExecutionToolResultError `json:"type,required"` + Type constant.CodeExecutionToolResultError `json:"type" api:"required"` paramObj } @@ -1369,9 +1369,9 @@ func (r *CodeExecutionToolResultErrorParam) UnmarshalJSON(data []byte) error { // tool) type Container struct { // Identifier for the container used in this request - ID string `json:"id,required"` + ID string `json:"id" api:"required"` // The time at which the container will expire. - ExpiresAt time.Time `json:"expires_at,required" format:"date-time"` + ExpiresAt time.Time `json:"expires_at" api:"required" format:"date-time"` // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. JSON struct { ID respjson.Field @@ -1389,8 +1389,8 @@ func (r *Container) UnmarshalJSON(data []byte) error { // Response model for a file uploaded to the container. type ContainerUploadBlock struct { - FileID string `json:"file_id,required"` - Type constant.ContainerUpload `json:"type,required"` + FileID string `json:"file_id" api:"required"` + Type constant.ContainerUpload `json:"type" api:"required"` // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. JSON struct { FileID respjson.Field @@ -1411,11 +1411,11 @@ func (r *ContainerUploadBlock) UnmarshalJSON(data []byte) error { // // The properties FileID, Type are required. type ContainerUploadBlockParam struct { - FileID string `json:"file_id,required"` + FileID string `json:"file_id" api:"required"` // Create a cache control breakpoint at this content block. CacheControl CacheControlEphemeralParam `json:"cache_control,omitzero"` // This field can be elided, and will marshal its zero value as "container_upload". - Type constant.ContainerUpload `json:"type,required"` + Type constant.ContainerUpload `json:"type" api:"required"` paramObj } @@ -2703,6 +2703,34 @@ func (u contentBlockParamUnionCaller) GetToolID() *string { return nil } +func init() { + apijson.RegisterCustomDecoder[[]ContentBlockParamUnion](func(node gjson.Result, value reflect.Value, defaultDecoder func(gjson.Result, reflect.Value) error) error { + if node.Type == gjson.String { + textBlock := TextBlockParam{Text: node.String(), Type: "text"} + contentUnion := ContentBlockParamUnion{OfText: &textBlock} + arrayValue := reflect.MakeSlice(value.Type(), 1, 1) + arrayValue.Index(0).Set(reflect.ValueOf(contentUnion)) + value.Set(arrayValue) + return nil + } + return defaultDecoder(node, value) + }) +} + +func init() { + apijson.RegisterCustomDecoder[[]ToolResultBlockParamContentUnion](func(node gjson.Result, value reflect.Value, defaultDecoder func(gjson.Result, reflect.Value) error) error { + if node.Type == gjson.String { + textBlock := TextBlockParam{Text: node.String(), Type: "text"} + contentUnion := ToolResultBlockParamContentUnion{OfText: &textBlock} + arrayValue := reflect.MakeSlice(value.Type(), 1, 1) + arrayValue.Index(0).Set(reflect.ValueOf(contentUnion)) + value.Set(arrayValue) + return nil + } + return defaultDecoder(node, value) + }) +} + func init() { apijson.RegisterUnion[ContentBlockParamUnion]( "type", @@ -2723,26 +2751,6 @@ func init() { apijson.Discriminator[ToolSearchToolResultBlockParam]("tool_search_tool_result"), apijson.Discriminator[ContainerUploadBlockParam]("container_upload"), ) - - // Register custom decoder for []ContentBlockParamUnion to handle string content - apijson.RegisterCustomDecoder[[]ContentBlockParamUnion](func(node gjson.Result, value reflect.Value, defaultDecoder func(gjson.Result, reflect.Value) error) error { - // If it's a string, convert it to a TextBlock automatically - if node.Type == gjson.String { - textBlock := TextBlockParam{ - Text: node.String(), - Type: "text", - } - contentUnion := ContentBlockParamUnion{ - OfText: &textBlock, - } - arrayValue := reflect.MakeSlice(value.Type(), 1, 1) - arrayValue.Index(0).Set(reflect.ValueOf(contentUnion)) - value.Set(arrayValue) - return nil - } - - return defaultDecoder(node, value) - }) } func init() { @@ -2771,6 +2779,15 @@ func init() { ) } +func init() { + apijson.RegisterUnion[ServerToolUseBlockParamCallerUnion]( + "type", + apijson.Discriminator[DirectCallerParam]("direct"), + apijson.Discriminator[ServerToolCallerParam]("code_execution_20250825"), + apijson.Discriminator[ServerToolCaller20260120Param]("code_execution_20260120"), + ) +} + func init() { apijson.RegisterUnion[TextCitationParamUnion]( "type", @@ -2787,6 +2804,7 @@ func init() { "type", apijson.Discriminator[ThinkingConfigEnabledParam]("enabled"), apijson.Discriminator[ThinkingConfigDisabledParam]("disabled"), + apijson.Discriminator[ThinkingConfigAdaptiveParam]("adaptive"), ) } @@ -2800,6 +2818,7 @@ func init() { ) } + func init() { apijson.RegisterUnion[ToolResultBlockParamContentUnion]( "type", @@ -2807,35 +2826,42 @@ func init() { apijson.Discriminator[ImageBlockParam]("image"), apijson.Discriminator[SearchResultBlockParam]("search_result"), apijson.Discriminator[DocumentBlockParam]("document"), + apijson.Discriminator[ToolReferenceBlockParam]("tool_reference"), ) +} - // Register custom decoder for []ToolResultBlockParamContentUnion to handle string content - apijson.RegisterCustomDecoder[[]ToolResultBlockParamContentUnion](func(node gjson.Result, value reflect.Value, defaultDecoder func(gjson.Result, reflect.Value) error) error { - // If it's a string, convert it to a TextBlock automatically - if node.Type == gjson.String { - textBlock := TextBlockParam{ - Text: node.String(), - Type: "text", - } - contentUnion := ToolResultBlockParamContentUnion{ - OfText: &textBlock, - } - arrayValue := reflect.MakeSlice(value.Type(), 1, 1) - arrayValue.Index(0).Set(reflect.ValueOf(contentUnion)) - value.Set(arrayValue) - return nil - } +func init() { + apijson.RegisterUnion[ToolUseBlockParamCallerUnion]( + "type", + apijson.Discriminator[DirectCallerParam]("direct"), + apijson.Discriminator[ServerToolCallerParam]("code_execution_20250825"), + apijson.Discriminator[ServerToolCaller20260120Param]("code_execution_20260120"), + ) +} - // If it's already an array, use the default decoder - return defaultDecoder(node, value) - }) +func init() { + apijson.RegisterUnion[WebFetchToolResultBlockParamCallerUnion]( + "type", + apijson.Discriminator[DirectCallerParam]("direct"), + apijson.Discriminator[ServerToolCallerParam]("code_execution_20250825"), + apijson.Discriminator[ServerToolCaller20260120Param]("code_execution_20260120"), + ) +} + +func init() { + apijson.RegisterUnion[WebSearchToolResultBlockParamCallerUnion]( + "type", + apijson.Discriminator[DirectCallerParam]("direct"), + apijson.Discriminator[ServerToolCallerParam]("code_execution_20250825"), + apijson.Discriminator[ServerToolCaller20260120Param]("code_execution_20260120"), + ) } // The properties Content, Type are required. type ContentBlockSourceParam struct { - Content ContentBlockSourceContentUnionParam `json:"content,omitzero,required"` + Content ContentBlockSourceContentUnionParam `json:"content,omitzero" api:"required"` // This field can be elided, and will marshal its zero value as "content". - Type constant.Content `json:"type,required"` + Type constant.Content `json:"type" api:"required"` paramObj } @@ -2958,17 +2984,9 @@ func (u ContentBlockSourceContentItemUnionParam) GetCacheControl() *CacheControl return nil } -func init() { - apijson.RegisterUnion[ContentBlockSourceContentItemUnionParam]( - "type", - apijson.Discriminator[TextBlockParam]("text"), - apijson.Discriminator[ImageBlockParam]("image"), - ) -} - // Tool invocation directly from the model. type DirectCaller struct { - Type constant.Direct `json:"type,required"` + Type constant.Direct `json:"type" api:"required"` // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. JSON struct { Type respjson.Field @@ -3002,7 +3020,7 @@ func NewDirectCallerParam() DirectCallerParam { // // This struct has a constant value, construct it with [NewDirectCallerParam]. type DirectCallerParam struct { - Type constant.Direct `json:"type,required"` + Type constant.Direct `json:"type" api:"required"` paramObj } @@ -3016,11 +3034,11 @@ func (r *DirectCallerParam) UnmarshalJSON(data []byte) error { type DocumentBlock struct { // Citation configuration for the document - Citations CitationsConfig `json:"citations,required"` - Source DocumentBlockSourceUnion `json:"source,required"` + Citations CitationsConfig `json:"citations" api:"required"` + Source DocumentBlockSourceUnion `json:"source" api:"required"` // The title of the document - Title string `json:"title,required"` - Type constant.Document `json:"type,required"` + Title string `json:"title" api:"required"` + Type constant.Document `json:"type" api:"required"` // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. JSON struct { Citations respjson.Field @@ -3104,14 +3122,14 @@ func (r *DocumentBlockSourceUnion) UnmarshalJSON(data []byte) error { // The properties Source, Type are required. type DocumentBlockParam struct { - Source DocumentBlockParamSourceUnion `json:"source,omitzero,required"` + Source DocumentBlockParamSourceUnion `json:"source,omitzero" api:"required"` Context param.Opt[string] `json:"context,omitzero"` Title param.Opt[string] `json:"title,omitzero"` // Create a cache control breakpoint at this content block. CacheControl CacheControlEphemeralParam `json:"cache_control,omitzero"` Citations CitationsConfigParam `json:"citations,omitzero"` // This field can be elided, and will marshal its zero value as "document". - Type constant.Document `json:"type,required"` + Type constant.Document `json:"type" api:"required"` paramObj } @@ -3204,23 +3222,13 @@ func (u DocumentBlockParamSourceUnion) GetType() *string { return nil } -func init() { - apijson.RegisterUnion[DocumentBlockParamSourceUnion]( - "type", - apijson.Discriminator[Base64PDFSourceParam]("base64"), - apijson.Discriminator[PlainTextSourceParam]("text"), - apijson.Discriminator[ContentBlockSourceParam]("content"), - apijson.Discriminator[URLPDFSourceParam]("url"), - ) -} - // Code execution result with encrypted stdout for PFC + web_search results. type EncryptedCodeExecutionResultBlock struct { - Content []CodeExecutionOutputBlock `json:"content,required"` - EncryptedStdout string `json:"encrypted_stdout,required"` - ReturnCode int64 `json:"return_code,required"` - Stderr string `json:"stderr,required"` - Type constant.EncryptedCodeExecutionResult `json:"type,required"` + Content []CodeExecutionOutputBlock `json:"content" api:"required"` + EncryptedStdout string `json:"encrypted_stdout" api:"required"` + ReturnCode int64 `json:"return_code" api:"required"` + Stderr string `json:"stderr" api:"required"` + Type constant.EncryptedCodeExecutionResult `json:"type" api:"required"` // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. JSON struct { Content respjson.Field @@ -3243,13 +3251,13 @@ func (r *EncryptedCodeExecutionResultBlock) UnmarshalJSON(data []byte) error { // // The properties Content, EncryptedStdout, ReturnCode, Stderr, Type are required. type EncryptedCodeExecutionResultBlockParam struct { - Content []CodeExecutionOutputBlockParam `json:"content,omitzero,required"` - EncryptedStdout string `json:"encrypted_stdout,required"` - ReturnCode int64 `json:"return_code,required"` - Stderr string `json:"stderr,required"` + Content []CodeExecutionOutputBlockParam `json:"content,omitzero" api:"required"` + EncryptedStdout string `json:"encrypted_stdout" api:"required"` + ReturnCode int64 `json:"return_code" api:"required"` + Stderr string `json:"stderr" api:"required"` // This field can be elided, and will marshal its zero value as // "encrypted_code_execution_result". - Type constant.EncryptedCodeExecutionResult `json:"type,required"` + Type constant.EncryptedCodeExecutionResult `json:"type" api:"required"` paramObj } @@ -3263,11 +3271,11 @@ func (r *EncryptedCodeExecutionResultBlockParam) UnmarshalJSON(data []byte) erro // The properties Source, Type are required. type ImageBlockParam struct { - Source ImageBlockParamSourceUnion `json:"source,omitzero,required"` + Source ImageBlockParamSourceUnion `json:"source,omitzero" api:"required"` // Create a cache control breakpoint at this content block. CacheControl CacheControlEphemeralParam `json:"cache_control,omitzero"` // This field can be elided, and will marshal its zero value as "image". - Type constant.Image `json:"type,required"` + Type constant.Image `json:"type" api:"required"` paramObj } @@ -3339,8 +3347,8 @@ func (u ImageBlockParamSourceUnion) GetType() *string { } type InputJSONDelta struct { - PartialJSON string `json:"partial_json,required"` - Type constant.InputJSONDelta `json:"type,required"` + PartialJSON string `json:"partial_json" api:"required"` + Type constant.InputJSONDelta `json:"type" api:"required"` // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. JSON struct { PartialJSON respjson.Field @@ -3359,9 +3367,9 @@ func (r *InputJSONDelta) UnmarshalJSON(data []byte) error { // The properties Schema, Type are required. type JSONOutputFormatParam struct { // The JSON schema of the format - Schema map[string]any `json:"schema,omitzero,required"` + Schema map[string]any `json:"schema,omitzero" api:"required"` // This field can be elided, and will marshal its zero value as "json_schema". - Type constant.JSONSchema `json:"type,required"` + Type constant.JSONSchema `json:"type" api:"required"` paramObj } @@ -3390,9 +3398,9 @@ type MemoryTool20250818Param struct { // This is how the tool will be called by the model and in `tool_use` blocks. // // This field can be elided, and will marshal its zero value as "memory". - Name constant.Memory `json:"name,required"` + Name constant.Memory `json:"name" api:"required"` // This field can be elided, and will marshal its zero value as "memory_20250818". - Type constant.Memory20250818 `json:"type,required"` + Type constant.Memory20250818 `json:"type" api:"required"` paramObj } @@ -3408,10 +3416,10 @@ type Message struct { // Unique object identifier. // // The format and length of IDs may change over time. - ID string `json:"id,required"` + ID string `json:"id" api:"required"` // Information about the container used in the request (for the code execution // tool) - Container Container `json:"container,required"` + Container Container `json:"container" api:"required"` // Content generated by the model. // // This is an array of content blocks, each of which has a `type` that determines @@ -3446,15 +3454,15 @@ type Message struct { // ```json // [{ "type": "text", "text": "B)" }] // ``` - Content []ContentBlockUnion `json:"content,required"` + Content []ContentBlockUnion `json:"content" api:"required"` // The model that will complete your prompt.\n\nSee // [models](https://docs.anthropic.com/en/docs/models-overview) for additional // details and options. - Model Model `json:"model,required"` + Model Model `json:"model" api:"required"` // Conversational role of the generated message. // // This will always be `"assistant"`. - Role constant.Assistant `json:"role,required"` + Role constant.Assistant `json:"role" api:"required"` // The reason that we stopped. // // This may be one the following values: @@ -3473,16 +3481,16 @@ type Message struct { // // Any of "end_turn", "max_tokens", "stop_sequence", "tool_use", "pause_turn", // "refusal". - StopReason StopReason `json:"stop_reason,required"` + StopReason StopReason `json:"stop_reason" api:"required"` // Which custom stop sequence was generated, if any. // // This value will be a non-null string if one of your custom stop sequences was // generated. - StopSequence string `json:"stop_sequence,required"` + StopSequence string `json:"stop_sequence" api:"required"` // Object type. // // For Messages, this is always `"message"`. - Type constant.Message `json:"type,required"` + Type constant.Message `json:"type" api:"required"` // Billing and rate-limit usage. // // Anthropic's API bills and rate-limits by token counts, as tokens represent the @@ -3498,7 +3506,7 @@ type Message struct { // // Total input tokens in a request is the summation of `input_tokens`, // `cache_creation_input_tokens`, and `cache_read_input_tokens`. - Usage Usage `json:"usage,required"` + Usage Usage `json:"usage" api:"required"` // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. JSON struct { ID respjson.Field @@ -3521,25 +3529,6 @@ func (r *Message) UnmarshalJSON(data []byte) error { return apijson.UnmarshalRoot(data, r) } -// The reason that we stopped. -// -// This may be one the following values: -// -// - `"end_turn"`: the model reached a natural stopping point -// - `"max_tokens"`: we exceeded the requested `max_tokens` or the model's maximum -// - `"stop_sequence"`: one of your provided custom `stop_sequences` was generated -// - `"tool_use"`: the model invoked one or more tools -// -// In non-streaming mode this value is always non-null. In streaming mode, it is -// null in the `message_start` event and non-null otherwise. -type MessageStopReason string - -const ( - MessageStopReasonEndTurn MessageStopReason = "end_turn" - MessageStopReasonMaxTokens MessageStopReason = "max_tokens" - MessageStopReasonStopSequence MessageStopReason = "stop_sequence" - MessageStopReasonToolUse MessageStopReason = "tool_use" -) func MessageCountTokensToolParamOfTool(inputSchema ToolInputSchemaParam, name string) MessageCountTokensToolUnionParam { var variant ToolParam @@ -3577,6 +3566,7 @@ type MessageCountTokensToolUnionParam struct { OfWebFetchTool20250910 *WebFetchTool20250910Param `json:",omitzero,inline"` OfWebSearchTool20260209 *WebSearchTool20260209Param `json:",omitzero,inline"` OfWebFetchTool20260209 *WebFetchTool20260209Param `json:",omitzero,inline"` + OfWebFetchTool20260309 *WebFetchTool20260309Param `json:",omitzero,inline"` OfToolSearchToolBm25_20251119 *ToolSearchToolBm25_20251119Param `json:",omitzero,inline"` OfToolSearchToolRegex20251119 *ToolSearchToolRegex20251119Param `json:",omitzero,inline"` paramUnion @@ -3596,6 +3586,7 @@ func (u MessageCountTokensToolUnionParam) MarshalJSON() ([]byte, error) { u.OfWebFetchTool20250910, u.OfWebSearchTool20260209, u.OfWebFetchTool20260209, + u.OfWebFetchTool20260309, u.OfToolSearchToolBm25_20251119, u.OfToolSearchToolRegex20251119) } @@ -3630,6 +3621,8 @@ func (u *MessageCountTokensToolUnionParam) asAny() any { return u.OfWebSearchTool20260209 } else if !param.IsOmitted(u.OfWebFetchTool20260209) { return u.OfWebFetchTool20260209 + } else if !param.IsOmitted(u.OfWebFetchTool20260309) { + return u.OfWebFetchTool20260309 } else if !param.IsOmitted(u.OfToolSearchToolBm25_20251119) { return u.OfToolSearchToolBm25_20251119 } else if !param.IsOmitted(u.OfToolSearchToolRegex20251119) { @@ -3670,6 +3663,14 @@ func (u MessageCountTokensToolUnionParam) GetMaxCharacters() *int64 { return nil } +// Returns a pointer to the underlying variant's property, if present. +func (u MessageCountTokensToolUnionParam) GetUseCache() *bool { + if vt := u.OfWebFetchTool20260309; vt != nil && vt.UseCache.Valid() { + return &vt.UseCache.Value + } + return nil +} + // Returns a pointer to the underlying variant's property, if present. func (u MessageCountTokensToolUnionParam) GetName() *string { if vt := u.OfTool; vt != nil { @@ -3698,6 +3699,8 @@ func (u MessageCountTokensToolUnionParam) GetName() *string { return (*string)(&vt.Name) } else if vt := u.OfWebFetchTool20260209; vt != nil { return (*string)(&vt.Name) + } else if vt := u.OfWebFetchTool20260309; vt != nil { + return (*string)(&vt.Name) } else if vt := u.OfToolSearchToolBm25_20251119; vt != nil { return (*string)(&vt.Name) } else if vt := u.OfToolSearchToolRegex20251119; vt != nil { @@ -3734,6 +3737,8 @@ func (u MessageCountTokensToolUnionParam) GetDeferLoading() *bool { return &vt.DeferLoading.Value } else if vt := u.OfWebFetchTool20260209; vt != nil && vt.DeferLoading.Valid() { return &vt.DeferLoading.Value + } else if vt := u.OfWebFetchTool20260309; vt != nil && vt.DeferLoading.Valid() { + return &vt.DeferLoading.Value } else if vt := u.OfToolSearchToolBm25_20251119; vt != nil && vt.DeferLoading.Valid() { return &vt.DeferLoading.Value } else if vt := u.OfToolSearchToolRegex20251119; vt != nil && vt.DeferLoading.Valid() { @@ -3770,6 +3775,8 @@ func (u MessageCountTokensToolUnionParam) GetStrict() *bool { return &vt.Strict.Value } else if vt := u.OfWebFetchTool20260209; vt != nil && vt.Strict.Valid() { return &vt.Strict.Value + } else if vt := u.OfWebFetchTool20260309; vt != nil && vt.Strict.Valid() { + return &vt.Strict.Value } else if vt := u.OfToolSearchToolBm25_20251119; vt != nil && vt.Strict.Valid() { return &vt.Strict.Value } else if vt := u.OfToolSearchToolRegex20251119; vt != nil && vt.Strict.Valid() { @@ -3806,6 +3813,8 @@ func (u MessageCountTokensToolUnionParam) GetType() *string { return (*string)(&vt.Type) } else if vt := u.OfWebFetchTool20260209; vt != nil { return (*string)(&vt.Type) + } else if vt := u.OfWebFetchTool20260309; vt != nil { + return (*string)(&vt.Type) } else if vt := u.OfToolSearchToolBm25_20251119; vt != nil { return (*string)(&vt.Type) } else if vt := u.OfToolSearchToolRegex20251119; vt != nil { @@ -3824,6 +3833,8 @@ func (u MessageCountTokensToolUnionParam) GetMaxUses() *int64 { return &vt.MaxUses.Value } else if vt := u.OfWebFetchTool20260209; vt != nil && vt.MaxUses.Valid() { return &vt.MaxUses.Value + } else if vt := u.OfWebFetchTool20260309; vt != nil && vt.MaxUses.Valid() { + return &vt.MaxUses.Value } return nil } @@ -3834,6 +3845,8 @@ func (u MessageCountTokensToolUnionParam) GetMaxContentTokens() *int64 { return &vt.MaxContentTokens.Value } else if vt := u.OfWebFetchTool20260209; vt != nil && vt.MaxContentTokens.Valid() { return &vt.MaxContentTokens.Value + } else if vt := u.OfWebFetchTool20260309; vt != nil && vt.MaxContentTokens.Valid() { + return &vt.MaxContentTokens.Value } return nil } @@ -3867,6 +3880,8 @@ func (u MessageCountTokensToolUnionParam) GetAllowedCallers() []string { return vt.AllowedCallers } else if vt := u.OfWebFetchTool20260209; vt != nil { return vt.AllowedCallers + } else if vt := u.OfWebFetchTool20260309; vt != nil { + return vt.AllowedCallers } else if vt := u.OfToolSearchToolBm25_20251119; vt != nil { return vt.AllowedCallers } else if vt := u.OfToolSearchToolRegex20251119; vt != nil { @@ -3903,6 +3918,8 @@ func (u MessageCountTokensToolUnionParam) GetCacheControl() *CacheControlEphemer return &vt.CacheControl } else if vt := u.OfWebFetchTool20260209; vt != nil { return &vt.CacheControl + } else if vt := u.OfWebFetchTool20260309; vt != nil { + return &vt.CacheControl } else if vt := u.OfToolSearchToolBm25_20251119; vt != nil { return &vt.CacheControl } else if vt := u.OfToolSearchToolRegex20251119; vt != nil { @@ -3941,6 +3958,8 @@ func (u MessageCountTokensToolUnionParam) GetAllowedDomains() []string { return vt.AllowedDomains } else if vt := u.OfWebFetchTool20260209; vt != nil { return vt.AllowedDomains + } else if vt := u.OfWebFetchTool20260309; vt != nil { + return vt.AllowedDomains } return nil } @@ -3956,6 +3975,8 @@ func (u MessageCountTokensToolUnionParam) GetBlockedDomains() []string { return vt.BlockedDomains } else if vt := u.OfWebFetchTool20260209; vt != nil { return vt.BlockedDomains + } else if vt := u.OfWebFetchTool20260309; vt != nil { + return vt.BlockedDomains } return nil } @@ -3976,21 +3997,23 @@ func (u MessageCountTokensToolUnionParam) GetCitations() *CitationsConfigParam { return &vt.Citations } else if vt := u.OfWebFetchTool20260209; vt != nil { return &vt.Citations + } else if vt := u.OfWebFetchTool20260309; vt != nil { + return &vt.Citations } return nil } type MessageDeltaUsage struct { // The cumulative number of input tokens used to create the cache entry. - CacheCreationInputTokens int64 `json:"cache_creation_input_tokens,required"` + CacheCreationInputTokens int64 `json:"cache_creation_input_tokens" api:"required"` // The cumulative number of input tokens read from the cache. - CacheReadInputTokens int64 `json:"cache_read_input_tokens,required"` + CacheReadInputTokens int64 `json:"cache_read_input_tokens" api:"required"` // The cumulative number of input tokens which were used. - InputTokens int64 `json:"input_tokens,required"` + InputTokens int64 `json:"input_tokens" api:"required"` // The cumulative number of output tokens which were used. - OutputTokens int64 `json:"output_tokens,required"` + OutputTokens int64 `json:"output_tokens" api:"required"` // The number of server tool requests. - ServerToolUse ServerToolUsage `json:"server_tool_use,required"` + ServerToolUse ServerToolUsage `json:"server_tool_use" api:"required"` // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. JSON struct { CacheCreationInputTokens respjson.Field @@ -4011,9 +4034,9 @@ func (r *MessageDeltaUsage) UnmarshalJSON(data []byte) error { // The properties Content, Role are required. type MessageParam struct { - Content []ContentBlockParamUnion `json:"content,omitzero,required"` + Content []ContentBlockParamUnion `json:"content,omitzero" api:"required"` // Any of "user", "assistant". - Role MessageParamRole `json:"role,omitzero,required"` + Role MessageParamRole `json:"role,omitzero" api:"required"` paramObj } @@ -4049,7 +4072,7 @@ const ( type MessageTokensCount struct { // The total number of tokens across the provided list of messages, system prompt, // and tools. - InputTokens int64 `json:"input_tokens,required"` + InputTokens int64 `json:"input_tokens" api:"required"` // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. JSON struct { InputTokens respjson.Field @@ -4085,54 +4108,27 @@ func (r *MetadataParam) UnmarshalJSON(data []byte) error { // The model that will complete your prompt.\n\nSee // [models](https://docs.anthropic.com/en/docs/models-overview) for additional // details and options. -type Model string +type Model = string const ( - ModelClaudeOpus4_6 Model = "claude-opus-4-6" - ModelClaudeSonnet4_6 Model = "claude-sonnet-4-6" - ModelClaudeOpus4_5_20251101 Model = "claude-opus-4-5-20251101" - ModelClaudeOpus4_5 Model = "claude-opus-4-5" - // Deprecated: Will reach end-of-life on February 19th, 2026. Please migrate to a - // newer model. Visit - // https://docs.anthropic.com/en/docs/resources/model-deprecations for more - // information. - ModelClaude3_7SonnetLatest Model = "claude-3-7-sonnet-latest" - // Deprecated: Will reach end-of-life on February 19th, 2026. Please migrate to a - // newer model. Visit - // https://docs.anthropic.com/en/docs/resources/model-deprecations for more - // information. - ModelClaude3_7Sonnet20250219 Model = "claude-3-7-sonnet-20250219" - // Deprecated: Will reach end-of-life on February 19th, 2026. Please migrate to a - // newer model. Visit - // https://docs.anthropic.com/en/docs/resources/model-deprecations for more - // information. - ModelClaude3_5HaikuLatest Model = "claude-3-5-haiku-latest" - // Deprecated: Will reach end-of-life on February 19th, 2026. Please migrate to a - // newer model. Visit - // https://docs.anthropic.com/en/docs/resources/model-deprecations for more - // information. - ModelClaude3_5Haiku20241022 Model = "claude-3-5-haiku-20241022" + ModelClaudeOpus4_6 Model = "claude-opus-4-6" + ModelClaudeSonnet4_6 Model = "claude-sonnet-4-6" ModelClaudeHaiku4_5 Model = "claude-haiku-4-5" ModelClaudeHaiku4_5_20251001 Model = "claude-haiku-4-5-20251001" - ModelClaudeSonnet4_20250514 Model = "claude-sonnet-4-20250514" - ModelClaudeSonnet4_0 Model = "claude-sonnet-4-0" - ModelClaude4Sonnet20250514 Model = "claude-4-sonnet-20250514" + ModelClaudeOpus4_5 Model = "claude-opus-4-5" + ModelClaudeOpus4_5_20251101 Model = "claude-opus-4-5-20251101" ModelClaudeSonnet4_5 Model = "claude-sonnet-4-5" ModelClaudeSonnet4_5_20250929 Model = "claude-sonnet-4-5-20250929" + ModelClaudeOpus4_1 Model = "claude-opus-4-1" + ModelClaudeOpus4_1_20250805 Model = "claude-opus-4-1-20250805" ModelClaudeOpus4_0 Model = "claude-opus-4-0" ModelClaudeOpus4_20250514 Model = "claude-opus-4-20250514" - ModelClaude4Opus20250514 Model = "claude-4-opus-20250514" - ModelClaudeOpus4_1_20250805 Model = "claude-opus-4-1-20250805" - // Deprecated: Will reach end-of-life on January 5th, 2026. Please migrate to a - // newer model. Visit - // https://docs.anthropic.com/en/docs/resources/model-deprecations for more - // information. - ModelClaude3OpusLatest Model = "claude-3-opus-latest" - // Deprecated: Will reach end-of-life on January 5th, 2026. Please migrate to a - // newer model. Visit + ModelClaudeSonnet4_0 Model = "claude-sonnet-4-0" + ModelClaudeSonnet4_20250514 Model = "claude-sonnet-4-20250514" + // Deprecated: Will reach end-of-life on April 20th, 2026. Please migrate to + // claude-haiku-4-5. Visit // https://docs.anthropic.com/en/docs/resources/model-deprecations for more // information. - ModelClaude_3_Opus_20240229 Model = "claude-3-opus-20240229" ModelClaude_3_Haiku_20240307 Model = "claude-3-haiku-20240307" ) @@ -4166,9 +4162,9 @@ const ( ) type PlainTextSource struct { - Data string `json:"data,required"` - MediaType constant.TextPlain `json:"media_type,required"` - Type constant.Text `json:"type,required"` + Data string `json:"data" api:"required"` + MediaType constant.TextPlain `json:"media_type" api:"required"` + Type constant.Text `json:"type" api:"required"` // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. JSON struct { Data respjson.Field @@ -4196,11 +4192,11 @@ func (r PlainTextSource) ToParam() PlainTextSourceParam { // The properties Data, MediaType, Type are required. type PlainTextSourceParam struct { - Data string `json:"data,required"` + Data string `json:"data" api:"required"` // This field can be elided, and will marshal its zero value as "text/plain". - MediaType constant.TextPlain `json:"media_type,required"` + MediaType constant.TextPlain `json:"media_type" api:"required"` // This field can be elided, and will marshal its zero value as "text". - Type constant.Text `json:"type,required"` + Type constant.Text `json:"type" api:"required"` paramObj } @@ -4317,9 +4313,9 @@ func (r *RawContentBlockDeltaUnion) UnmarshalJSON(data []byte) error { } type ContentBlockDeltaEvent struct { - Delta RawContentBlockDeltaUnion `json:"delta,required"` - Index int64 `json:"index,required"` - Type constant.ContentBlockDelta `json:"type,required"` + Delta RawContentBlockDeltaUnion `json:"delta" api:"required"` + Index int64 `json:"index" api:"required"` + Type constant.ContentBlockDelta `json:"type" api:"required"` // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. JSON struct { Delta respjson.Field @@ -4338,9 +4334,9 @@ func (r *ContentBlockDeltaEvent) UnmarshalJSON(data []byte) error { type ContentBlockStartEvent struct { // Response model for a file uploaded to the container. - ContentBlock ContentBlockStartEventContentBlockUnion `json:"content_block,required"` - Index int64 `json:"index,required"` - Type constant.ContentBlockStart `json:"type,required"` + ContentBlock ContentBlockStartEventContentBlockUnion `json:"content_block" api:"required"` + Index int64 `json:"index" api:"required"` + Type constant.ContentBlockStart `json:"type" api:"required"` // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. JSON struct { ContentBlock respjson.Field @@ -4697,8 +4693,8 @@ func (r *ContentBlockStartEventContentBlockUnionContentContent) UnmarshalJSON(da } type ContentBlockStopEvent struct { - Index int64 `json:"index,required"` - Type constant.ContentBlockStop `json:"type,required"` + Index int64 `json:"index" api:"required"` + Type constant.ContentBlockStop `json:"type" api:"required"` // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. JSON struct { Index respjson.Field @@ -4715,8 +4711,8 @@ func (r *ContentBlockStopEvent) UnmarshalJSON(data []byte) error { } type MessageDeltaEvent struct { - Delta MessageDeltaEventDelta `json:"delta,required"` - Type constant.MessageDelta `json:"type,required"` + Delta MessageDeltaEventDelta `json:"delta" api:"required"` + Type constant.MessageDelta `json:"type" api:"required"` // Billing and rate-limit usage. // // Anthropic's API bills and rate-limits by token counts, as tokens represent the @@ -4732,7 +4728,7 @@ type MessageDeltaEvent struct { // // Total input tokens in a request is the summation of `input_tokens`, // `cache_creation_input_tokens`, and `cache_read_input_tokens`. - Usage MessageDeltaUsage `json:"usage,required"` + Usage MessageDeltaUsage `json:"usage" api:"required"` // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. JSON struct { Delta respjson.Field @@ -4752,11 +4748,11 @@ func (r *MessageDeltaEvent) UnmarshalJSON(data []byte) error { type MessageDeltaEventDelta struct { // Information about the container used in the request (for the code execution // tool) - Container Container `json:"container,required"` + Container Container `json:"container" api:"required"` // Any of "end_turn", "max_tokens", "stop_sequence", "tool_use", "pause_turn", // "refusal". - StopReason StopReason `json:"stop_reason,required"` - StopSequence string `json:"stop_sequence,required"` + StopReason StopReason `json:"stop_reason" api:"required"` + StopSequence string `json:"stop_sequence" api:"required"` // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. JSON struct { Container respjson.Field @@ -4774,8 +4770,8 @@ func (r *MessageDeltaEventDelta) UnmarshalJSON(data []byte) error { } type MessageStartEvent struct { - Message Message `json:"message,required"` - Type constant.MessageStart `json:"type,required"` + Message Message `json:"message" api:"required"` + Type constant.MessageStart `json:"type" api:"required"` // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. JSON struct { Message respjson.Field @@ -4792,7 +4788,7 @@ func (r *MessageStartEvent) UnmarshalJSON(data []byte) error { } type MessageStopEvent struct { - Type constant.MessageStop `json:"type,required"` + Type constant.MessageStop `json:"type" api:"required"` // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. JSON struct { Type respjson.Field @@ -4962,8 +4958,8 @@ func (r *MessageStreamEventUnionDelta) UnmarshalJSON(data []byte) error { } type RedactedThinkingBlock struct { - Data string `json:"data,required"` - Type constant.RedactedThinking `json:"type,required"` + Data string `json:"data" api:"required"` + Type constant.RedactedThinking `json:"type" api:"required"` // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. JSON struct { Data respjson.Field @@ -4981,10 +4977,10 @@ func (r *RedactedThinkingBlock) UnmarshalJSON(data []byte) error { // The properties Data, Type are required. type RedactedThinkingBlockParam struct { - Data string `json:"data,required"` + Data string `json:"data" api:"required"` // This field can be elided, and will marshal its zero value as // "redacted_thinking". - Type constant.RedactedThinking `json:"type,required"` + Type constant.RedactedThinking `json:"type" api:"required"` paramObj } @@ -4998,14 +4994,14 @@ func (r *RedactedThinkingBlockParam) UnmarshalJSON(data []byte) error { // The properties Content, Source, Title, Type are required. type SearchResultBlockParam struct { - Content []TextBlockParam `json:"content,omitzero,required"` - Source string `json:"source,required"` - Title string `json:"title,required"` + Content []TextBlockParam `json:"content,omitzero" api:"required"` + Source string `json:"source" api:"required"` + Title string `json:"title" api:"required"` // Create a cache control breakpoint at this content block. CacheControl CacheControlEphemeralParam `json:"cache_control,omitzero"` Citations CitationsConfigParam `json:"citations,omitzero"` // This field can be elided, and will marshal its zero value as "search_result". - Type constant.SearchResult `json:"type,required"` + Type constant.SearchResult `json:"type" api:"required"` paramObj } @@ -5019,8 +5015,8 @@ func (r *SearchResultBlockParam) UnmarshalJSON(data []byte) error { // Tool invocation generated by a server-side tool. type ServerToolCaller struct { - ToolID string `json:"tool_id,required"` - Type constant.CodeExecution20250825 `json:"type,required"` + ToolID string `json:"tool_id" api:"required"` + Type constant.CodeExecution20250825 `json:"type" api:"required"` // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. JSON struct { ToolID respjson.Field @@ -5049,10 +5045,10 @@ func (r ServerToolCaller) ToParam() ServerToolCallerParam { // // The properties ToolID, Type are required. type ServerToolCallerParam struct { - ToolID string `json:"tool_id,required"` + ToolID string `json:"tool_id" api:"required"` // This field can be elided, and will marshal its zero value as // "code_execution_20250825". - Type constant.CodeExecution20250825 `json:"type,required"` + Type constant.CodeExecution20250825 `json:"type" api:"required"` paramObj } @@ -5065,8 +5061,8 @@ func (r *ServerToolCallerParam) UnmarshalJSON(data []byte) error { } type ServerToolCaller20260120 struct { - ToolID string `json:"tool_id,required"` - Type constant.CodeExecution20260120 `json:"type,required"` + ToolID string `json:"tool_id" api:"required"` + Type constant.CodeExecution20260120 `json:"type" api:"required"` // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. JSON struct { ToolID respjson.Field @@ -5094,10 +5090,10 @@ func (r ServerToolCaller20260120) ToParam() ServerToolCaller20260120Param { // The properties ToolID, Type are required. type ServerToolCaller20260120Param struct { - ToolID string `json:"tool_id,required"` + ToolID string `json:"tool_id" api:"required"` // This field can be elided, and will marshal its zero value as // "code_execution_20260120". - Type constant.CodeExecution20260120 `json:"type,required"` + Type constant.CodeExecution20260120 `json:"type" api:"required"` paramObj } @@ -5111,9 +5107,9 @@ func (r *ServerToolCaller20260120Param) UnmarshalJSON(data []byte) error { type ServerToolUsage struct { // The number of web fetch tool requests. - WebFetchRequests int64 `json:"web_fetch_requests,required"` + WebFetchRequests int64 `json:"web_fetch_requests" api:"required"` // The number of web search tool requests. - WebSearchRequests int64 `json:"web_search_requests,required"` + WebSearchRequests int64 `json:"web_search_requests" api:"required"` // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. JSON struct { WebFetchRequests respjson.Field @@ -5130,14 +5126,14 @@ func (r *ServerToolUsage) UnmarshalJSON(data []byte) error { } type ServerToolUseBlock struct { - ID string `json:"id,required"` + ID string `json:"id" api:"required"` // Tool invocation directly from the model. - Caller ServerToolUseBlockCallerUnion `json:"caller,required"` - Input any `json:"input,required"` + Caller ServerToolUseBlockCallerUnion `json:"caller" api:"required"` + Input any `json:"input" api:"required"` // Any of "web_search", "web_fetch", "code_execution", "bash_code_execution", // "text_editor_code_execution", "tool_search_tool_regex", "tool_search_tool_bm25". - Name ServerToolUseBlockName `json:"name,required"` - Type constant.ServerToolUse `json:"type,required"` + Name ServerToolUseBlockName `json:"name" api:"required"` + Type constant.ServerToolUse `json:"type" api:"required"` // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. JSON struct { ID respjson.Field @@ -5241,17 +5237,17 @@ const ( // The properties ID, Input, Name, Type are required. type ServerToolUseBlockParam struct { - ID string `json:"id,required"` - Input any `json:"input,omitzero,required"` + ID string `json:"id" api:"required"` + Input any `json:"input,omitzero" api:"required"` + // Any of "web_search", "web_fetch", "code_execution", "bash_code_execution", + // "text_editor_code_execution", "tool_search_tool_regex", "tool_search_tool_bm25". + Name ServerToolUseBlockParamName `json:"name,omitzero" api:"required"` // Create a cache control breakpoint at this content block. CacheControl CacheControlEphemeralParam `json:"cache_control,omitzero"` // Tool invocation directly from the model. Caller ServerToolUseBlockParamCallerUnion `json:"caller,omitzero"` - // Any of "web_search", "web_fetch", "code_execution", "bash_code_execution", - // "text_editor_code_execution", "tool_search_tool_regex", "tool_search_tool_bm25". - Name ServerToolUseBlockParamName `json:"name,required"` // This field can be elided, and will marshal its zero value as "server_tool_use". - Type constant.ServerToolUse `json:"type,required"` + Type constant.ServerToolUse `json:"type" api:"required"` paramObj } @@ -5325,18 +5321,9 @@ func (u ServerToolUseBlockParamCallerUnion) GetToolID() *string { return nil } -func init() { - apijson.RegisterUnion[ServerToolUseBlockParamCallerUnion]( - "type", - apijson.Discriminator[DirectCallerParam]("direct"), - apijson.Discriminator[ServerToolCallerParam]("code_execution_20250825"), - apijson.Discriminator[ServerToolCaller20260120Param]("code_execution_20260120"), - ) -} - type SignatureDelta struct { - Signature string `json:"signature,required"` - Type constant.SignatureDelta `json:"type,required"` + Signature string `json:"signature" api:"required"` + Type constant.SignatureDelta `json:"type" api:"required"` // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. JSON struct { Signature respjson.Field @@ -5369,9 +5356,9 @@ type TextBlock struct { // The type of citation returned will depend on the type of document being cited. // Citing a PDF results in `page_location`, plain text results in `char_location`, // and content document results in `content_block_location`. - Citations []TextCitationUnion `json:"citations,required"` - Text string `json:"text,required"` - Type constant.Text `json:"type,required"` + Citations []TextCitationUnion `json:"citations" api:"required"` + Text string `json:"text" api:"required"` + Type constant.Text `json:"type" api:"required"` // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. JSON struct { Citations respjson.Field @@ -5390,12 +5377,12 @@ func (r *TextBlock) UnmarshalJSON(data []byte) error { // The properties Text, Type are required. type TextBlockParam struct { - Text string `json:"text,required"` + Text string `json:"text" api:"required"` Citations []TextCitationParamUnion `json:"citations,omitzero"` // Create a cache control breakpoint at this content block. CacheControl CacheControlEphemeralParam `json:"cache_control,omitzero"` // This field can be elided, and will marshal its zero value as "text". - Type constant.Text `json:"type,required"` + Type constant.Text `json:"type" api:"required"` paramObj } @@ -5723,8 +5710,8 @@ func (u TextCitationParamUnion) GetTitle() *string { } type TextDelta struct { - Text string `json:"text,required"` - Type constant.TextDelta `json:"type,required"` + Text string `json:"text" api:"required"` + Type constant.TextDelta `json:"type" api:"required"` // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. JSON struct { Text respjson.Field @@ -5741,8 +5728,8 @@ func (r *TextDelta) UnmarshalJSON(data []byte) error { } type TextEditorCodeExecutionCreateResultBlock struct { - IsFileUpdate bool `json:"is_file_update,required"` - Type constant.TextEditorCodeExecutionCreateResult `json:"type,required"` + IsFileUpdate bool `json:"is_file_update" api:"required"` + Type constant.TextEditorCodeExecutionCreateResult `json:"type" api:"required"` // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. JSON struct { IsFileUpdate respjson.Field @@ -5760,10 +5747,10 @@ func (r *TextEditorCodeExecutionCreateResultBlock) UnmarshalJSON(data []byte) er // The properties IsFileUpdate, Type are required. type TextEditorCodeExecutionCreateResultBlockParam struct { - IsFileUpdate bool `json:"is_file_update,required"` + IsFileUpdate bool `json:"is_file_update" api:"required"` // This field can be elided, and will marshal its zero value as // "text_editor_code_execution_create_result". - Type constant.TextEditorCodeExecutionCreateResult `json:"type,required"` + Type constant.TextEditorCodeExecutionCreateResult `json:"type" api:"required"` paramObj } @@ -5776,12 +5763,12 @@ func (r *TextEditorCodeExecutionCreateResultBlockParam) UnmarshalJSON(data []byt } type TextEditorCodeExecutionStrReplaceResultBlock struct { - Lines []string `json:"lines,required"` - NewLines int64 `json:"new_lines,required"` - NewStart int64 `json:"new_start,required"` - OldLines int64 `json:"old_lines,required"` - OldStart int64 `json:"old_start,required"` - Type constant.TextEditorCodeExecutionStrReplaceResult `json:"type,required"` + Lines []string `json:"lines" api:"required"` + NewLines int64 `json:"new_lines" api:"required"` + NewStart int64 `json:"new_start" api:"required"` + OldLines int64 `json:"old_lines" api:"required"` + OldStart int64 `json:"old_start" api:"required"` + Type constant.TextEditorCodeExecutionStrReplaceResult `json:"type" api:"required"` // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. JSON struct { Lines respjson.Field @@ -5810,7 +5797,7 @@ type TextEditorCodeExecutionStrReplaceResultBlockParam struct { Lines []string `json:"lines,omitzero"` // This field can be elided, and will marshal its zero value as // "text_editor_code_execution_str_replace_result". - Type constant.TextEditorCodeExecutionStrReplaceResult `json:"type,required"` + Type constant.TextEditorCodeExecutionStrReplaceResult `json:"type" api:"required"` paramObj } @@ -5823,9 +5810,9 @@ func (r *TextEditorCodeExecutionStrReplaceResultBlockParam) UnmarshalJSON(data [ } type TextEditorCodeExecutionToolResultBlock struct { - Content TextEditorCodeExecutionToolResultBlockContentUnion `json:"content,required"` - ToolUseID string `json:"tool_use_id,required"` - Type constant.TextEditorCodeExecutionToolResult `json:"type,required"` + Content TextEditorCodeExecutionToolResultBlockContentUnion `json:"content" api:"required"` + ToolUseID string `json:"tool_use_id" api:"required"` + Type constant.TextEditorCodeExecutionToolResult `json:"type" api:"required"` // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. JSON struct { Content respjson.Field @@ -5925,13 +5912,13 @@ func (r *TextEditorCodeExecutionToolResultBlockContentUnion) UnmarshalJSON(data // The properties Content, ToolUseID, Type are required. type TextEditorCodeExecutionToolResultBlockParam struct { - Content TextEditorCodeExecutionToolResultBlockParamContentUnion `json:"content,omitzero,required"` - ToolUseID string `json:"tool_use_id,required"` + Content TextEditorCodeExecutionToolResultBlockParamContentUnion `json:"content,omitzero" api:"required"` + ToolUseID string `json:"tool_use_id" api:"required"` // Create a cache control breakpoint at this content block. CacheControl CacheControlEphemeralParam `json:"cache_control,omitzero"` // This field can be elided, and will marshal its zero value as // "text_editor_code_execution_tool_result". - Type constant.TextEditorCodeExecutionToolResult `json:"type,required"` + Type constant.TextEditorCodeExecutionToolResult `json:"type" api:"required"` paramObj } @@ -6095,9 +6082,9 @@ func (u TextEditorCodeExecutionToolResultBlockParamContentUnion) GetType() *stri type TextEditorCodeExecutionToolResultError struct { // Any of "invalid_tool_input", "unavailable", "too_many_requests", // "execution_time_exceeded", "file_not_found". - ErrorCode TextEditorCodeExecutionToolResultErrorCode `json:"error_code,required"` - ErrorMessage string `json:"error_message,required"` - Type constant.TextEditorCodeExecutionToolResultError `json:"type,required"` + ErrorCode TextEditorCodeExecutionToolResultErrorCode `json:"error_code" api:"required"` + ErrorMessage string `json:"error_message" api:"required"` + Type constant.TextEditorCodeExecutionToolResultError `json:"type" api:"required"` // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. JSON struct { ErrorCode respjson.Field @@ -6128,11 +6115,11 @@ const ( type TextEditorCodeExecutionToolResultErrorParam struct { // Any of "invalid_tool_input", "unavailable", "too_many_requests", // "execution_time_exceeded", "file_not_found". - ErrorCode TextEditorCodeExecutionToolResultErrorCode `json:"error_code,omitzero,required"` + ErrorCode TextEditorCodeExecutionToolResultErrorCode `json:"error_code,omitzero" api:"required"` ErrorMessage param.Opt[string] `json:"error_message,omitzero"` // This field can be elided, and will marshal its zero value as // "text_editor_code_execution_tool_result_error". - Type constant.TextEditorCodeExecutionToolResultError `json:"type,required"` + Type constant.TextEditorCodeExecutionToolResultError `json:"type" api:"required"` paramObj } @@ -6145,13 +6132,13 @@ func (r *TextEditorCodeExecutionToolResultErrorParam) UnmarshalJSON(data []byte) } type TextEditorCodeExecutionViewResultBlock struct { - Content string `json:"content,required"` + Content string `json:"content" api:"required"` // Any of "text", "image", "pdf". - FileType TextEditorCodeExecutionViewResultBlockFileType `json:"file_type,required"` - NumLines int64 `json:"num_lines,required"` - StartLine int64 `json:"start_line,required"` - TotalLines int64 `json:"total_lines,required"` - Type constant.TextEditorCodeExecutionViewResult `json:"type,required"` + FileType TextEditorCodeExecutionViewResultBlockFileType `json:"file_type" api:"required"` + NumLines int64 `json:"num_lines" api:"required"` + StartLine int64 `json:"start_line" api:"required"` + TotalLines int64 `json:"total_lines" api:"required"` + Type constant.TextEditorCodeExecutionViewResult `json:"type" api:"required"` // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. JSON struct { Content respjson.Field @@ -6181,15 +6168,15 @@ const ( // The properties Content, FileType, Type are required. type TextEditorCodeExecutionViewResultBlockParam struct { - Content string `json:"content,required"` + Content string `json:"content" api:"required"` // Any of "text", "image", "pdf". - FileType TextEditorCodeExecutionViewResultBlockParamFileType `json:"file_type,omitzero,required"` + FileType TextEditorCodeExecutionViewResultBlockParamFileType `json:"file_type,omitzero" api:"required"` NumLines param.Opt[int64] `json:"num_lines,omitzero"` StartLine param.Opt[int64] `json:"start_line,omitzero"` TotalLines param.Opt[int64] `json:"total_lines,omitzero"` // This field can be elided, and will marshal its zero value as // "text_editor_code_execution_view_result". - Type constant.TextEditorCodeExecutionViewResult `json:"type,required"` + Type constant.TextEditorCodeExecutionViewResult `json:"type" api:"required"` paramObj } @@ -6210,9 +6197,9 @@ const ( ) type ThinkingBlock struct { - Signature string `json:"signature,required"` - Thinking string `json:"thinking,required"` - Type constant.Thinking `json:"type,required"` + Signature string `json:"signature" api:"required"` + Thinking string `json:"thinking" api:"required"` + Type constant.Thinking `json:"type" api:"required"` // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. JSON struct { Signature respjson.Field @@ -6231,10 +6218,10 @@ func (r *ThinkingBlock) UnmarshalJSON(data []byte) error { // The properties Signature, Thinking, Type are required. type ThinkingBlockParam struct { - Signature string `json:"signature,required"` - Thinking string `json:"thinking,required"` + Signature string `json:"signature" api:"required"` + Thinking string `json:"thinking" api:"required"` // This field can be elided, and will marshal its zero value as "thinking". - Type constant.Thinking `json:"type,required"` + Type constant.Thinking `json:"type" api:"required"` paramObj } @@ -6246,16 +6233,17 @@ func (r *ThinkingBlockParam) UnmarshalJSON(data []byte) error { return apijson.UnmarshalRoot(data, r) } -func NewThinkingConfigAdaptiveParam() ThinkingConfigAdaptiveParam { - return ThinkingConfigAdaptiveParam{ - Type: "adaptive", - } -} - -// This struct has a constant value, construct it with -// [NewThinkingConfigAdaptiveParam]. +// The property Type is required. type ThinkingConfigAdaptiveParam struct { - Type constant.Adaptive `json:"type,required"` + // Controls how thinking content appears in the response. When set to `summarized`, + // thinking is returned normally. When set to `omitted`, thinking content is + // redacted but a signature is returned for multi-turn continuity. Defaults to + // `summarized`. + // + // Any of "summarized", "omitted". + Display ThinkingConfigAdaptiveDisplay `json:"display,omitzero"` + // This field can be elided, and will marshal its zero value as "adaptive". + Type constant.Adaptive `json:"type" api:"required"` paramObj } @@ -6267,6 +6255,17 @@ func (r *ThinkingConfigAdaptiveParam) UnmarshalJSON(data []byte) error { return apijson.UnmarshalRoot(data, r) } +// Controls how thinking content appears in the response. When set to `summarized`, +// thinking is returned normally. When set to `omitted`, thinking content is +// redacted but a signature is returned for multi-turn continuity. Defaults to +// `summarized`. +type ThinkingConfigAdaptiveDisplay string + +const ( + ThinkingConfigAdaptiveDisplaySummarized ThinkingConfigAdaptiveDisplay = "summarized" + ThinkingConfigAdaptiveDisplayOmitted ThinkingConfigAdaptiveDisplay = "omitted" +) + func NewThinkingConfigDisabledParam() ThinkingConfigDisabledParam { return ThinkingConfigDisabledParam{ Type: "disabled", @@ -6276,7 +6275,7 @@ func NewThinkingConfigDisabledParam() ThinkingConfigDisabledParam { // This struct has a constant value, construct it with // [NewThinkingConfigDisabledParam]. type ThinkingConfigDisabledParam struct { - Type constant.Disabled `json:"type,required"` + Type constant.Disabled `json:"type" api:"required"` paramObj } @@ -6299,9 +6298,16 @@ type ThinkingConfigEnabledParam struct { // See // [extended thinking](https://docs.claude.com/en/docs/build-with-claude/extended-thinking) // for details. - BudgetTokens int64 `json:"budget_tokens,required"` + BudgetTokens int64 `json:"budget_tokens" api:"required"` + // Controls how thinking content appears in the response. When set to `summarized`, + // thinking is returned normally. When set to `omitted`, thinking content is + // redacted but a signature is returned for multi-turn continuity. Defaults to + // `summarized`. + // + // Any of "summarized", "omitted". + Display ThinkingConfigEnabledDisplay `json:"display,omitzero"` // This field can be elided, and will marshal its zero value as "enabled". - Type constant.Enabled `json:"type,required"` + Type constant.Enabled `json:"type" api:"required"` paramObj } @@ -6313,6 +6319,17 @@ func (r *ThinkingConfigEnabledParam) UnmarshalJSON(data []byte) error { return apijson.UnmarshalRoot(data, r) } +// Controls how thinking content appears in the response. When set to `summarized`, +// thinking is returned normally. When set to `omitted`, thinking content is +// redacted but a signature is returned for multi-turn continuity. Defaults to +// `summarized`. +type ThinkingConfigEnabledDisplay string + +const ( + ThinkingConfigEnabledDisplaySummarized ThinkingConfigEnabledDisplay = "summarized" + ThinkingConfigEnabledDisplayOmitted ThinkingConfigEnabledDisplay = "omitted" +) + func ThinkingConfigParamOfEnabled(budgetTokens int64) ThinkingConfigParamUnion { var enabled ThinkingConfigEnabledParam enabled.BudgetTokens = budgetTokens @@ -6367,10 +6384,19 @@ func (u ThinkingConfigParamUnion) GetType() *string { return nil } +// Returns a pointer to the underlying variant's property, if present. +func (u ThinkingConfigParamUnion) GetDisplay() *string { + if vt := u.OfEnabled; vt != nil { + return (*string)(&vt.Display) + } else if vt := u.OfAdaptive; vt != nil { + return (*string)(&vt.Display) + } + return nil +} type ThinkingDelta struct { - Thinking string `json:"thinking,required"` - Type constant.ThinkingDelta `json:"type,required"` + Thinking string `json:"thinking" api:"required"` + Type constant.ThinkingDelta `json:"type" api:"required"` // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. JSON struct { Thinking respjson.Field @@ -6392,11 +6418,11 @@ type ToolParam struct { // // This defines the shape of the `input` that your tool accepts and that the model // will produce. - InputSchema ToolInputSchemaParam `json:"input_schema,omitzero,required"` + InputSchema ToolInputSchemaParam `json:"input_schema,omitzero" api:"required"` // Name of the tool. // // This is how the tool will be called by the model and in `tool_use` blocks. - Name string `json:"name,required"` + Name string `json:"name" api:"required"` // Enable eager input streaming for this tool. When true, tool input parameters // will be streamed incrementally as they are generated, and types will be inferred // on-the-fly rather than buffering the full JSON output. When false, streaming is @@ -6443,7 +6469,7 @@ type ToolInputSchemaParam struct { Properties any `json:"properties,omitzero"` Required []string `json:"required,omitzero"` // This field can be elided, and will marshal its zero value as "object". - Type constant.Object `json:"type,required"` + Type constant.Object `json:"type" api:"required"` ExtraFields map[string]any `json:"-"` paramObj } @@ -6479,9 +6505,9 @@ type ToolBash20250124Param struct { // This is how the tool will be called by the model and in `tool_use` blocks. // // This field can be elided, and will marshal its zero value as "bash". - Name constant.Bash `json:"name,required"` + Name constant.Bash `json:"name" api:"required"` // This field can be elided, and will marshal its zero value as "bash_20250124". - Type constant.Bash20250124 `json:"type,required"` + Type constant.Bash20250124 `json:"type" api:"required"` paramObj } @@ -6574,7 +6600,7 @@ type ToolChoiceAnyParam struct { // use. DisableParallelToolUse param.Opt[bool] `json:"disable_parallel_tool_use,omitzero"` // This field can be elided, and will marshal its zero value as "any". - Type constant.Any `json:"type,required"` + Type constant.Any `json:"type" api:"required"` paramObj } @@ -6596,7 +6622,7 @@ type ToolChoiceAutoParam struct { // use. DisableParallelToolUse param.Opt[bool] `json:"disable_parallel_tool_use,omitzero"` // This field can be elided, and will marshal its zero value as "auto". - Type constant.Auto `json:"type,required"` + Type constant.Auto `json:"type" api:"required"` paramObj } @@ -6618,7 +6644,7 @@ func NewToolChoiceNoneParam() ToolChoiceNoneParam { // // This struct has a constant value, construct it with [NewToolChoiceNoneParam]. type ToolChoiceNoneParam struct { - Type constant.None `json:"type,required"` + Type constant.None `json:"type" api:"required"` paramObj } @@ -6635,14 +6661,14 @@ func (r *ToolChoiceNoneParam) UnmarshalJSON(data []byte) error { // The properties Name, Type are required. type ToolChoiceToolParam struct { // The name of the tool to use. - Name string `json:"name,required"` + Name string `json:"name" api:"required"` // Whether to disable parallel tool use. // // Defaults to `false`. If set to `true`, the model will output exactly one tool // use. DisableParallelToolUse param.Opt[bool] `json:"disable_parallel_tool_use,omitzero"` // This field can be elided, and will marshal its zero value as "tool". - Type constant.Tool `json:"type,required"` + Type constant.Tool `json:"type" api:"required"` paramObj } @@ -6655,8 +6681,8 @@ func (r *ToolChoiceToolParam) UnmarshalJSON(data []byte) error { } type ToolReferenceBlock struct { - ToolName string `json:"tool_name,required"` - Type constant.ToolReference `json:"type,required"` + ToolName string `json:"tool_name" api:"required"` + Type constant.ToolReference `json:"type" api:"required"` // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. JSON struct { ToolName respjson.Field @@ -6676,11 +6702,11 @@ func (r *ToolReferenceBlock) UnmarshalJSON(data []byte) error { // // The properties ToolName, Type are required. type ToolReferenceBlockParam struct { - ToolName string `json:"tool_name,required"` + ToolName string `json:"tool_name" api:"required"` // Create a cache control breakpoint at this content block. CacheControl CacheControlEphemeralParam `json:"cache_control,omitzero"` // This field can be elided, and will marshal its zero value as "tool_reference". - Type constant.ToolReference `json:"type,required"` + Type constant.ToolReference `json:"type" api:"required"` paramObj } @@ -6694,13 +6720,13 @@ func (r *ToolReferenceBlockParam) UnmarshalJSON(data []byte) error { // The properties ToolUseID, Type are required. type ToolResultBlockParam struct { - ToolUseID string `json:"tool_use_id,required"` + ToolUseID string `json:"tool_use_id" api:"required"` IsError param.Opt[bool] `json:"is_error,omitzero"` // Create a cache control breakpoint at this content block. CacheControl CacheControlEphemeralParam `json:"cache_control,omitzero"` Content []ToolResultBlockParamContentUnion `json:"content,omitzero"` // This field can be elided, and will marshal its zero value as "tool_result". - Type constant.ToolResult `json:"type,required"` + Type constant.ToolResult `json:"type" api:"required"` paramObj } @@ -6947,11 +6973,10 @@ func (u toolResultBlockParamContentUnionSource) GetURL() *string { return nil } - // The properties Name, Type are required. type ToolSearchToolBm25_20251119Param struct { // Any of "tool_search_tool_bm25_20251119", "tool_search_tool_bm25". - Type ToolSearchToolBm25_20251119Type `json:"type,omitzero,required"` + Type ToolSearchToolBm25_20251119Type `json:"type,omitzero" api:"required"` // If true, tool will not be included in initial system prompt. Only loaded when // returned via tool_reference from tool search. DeferLoading param.Opt[bool] `json:"defer_loading,omitzero"` @@ -6967,7 +6992,7 @@ type ToolSearchToolBm25_20251119Param struct { // // This field can be elided, and will marshal its zero value as // "tool_search_tool_bm25". - Name constant.ToolSearchToolBm25 `json:"name,required"` + Name constant.ToolSearchToolBm25 `json:"name" api:"required"` paramObj } @@ -6989,7 +7014,7 @@ const ( // The properties Name, Type are required. type ToolSearchToolRegex20251119Param struct { // Any of "tool_search_tool_regex_20251119", "tool_search_tool_regex". - Type ToolSearchToolRegex20251119Type `json:"type,omitzero,required"` + Type ToolSearchToolRegex20251119Type `json:"type,omitzero" api:"required"` // If true, tool will not be included in initial system prompt. Only loaded when // returned via tool_reference from tool search. DeferLoading param.Opt[bool] `json:"defer_loading,omitzero"` @@ -7005,7 +7030,7 @@ type ToolSearchToolRegex20251119Param struct { // // This field can be elided, and will marshal its zero value as // "tool_search_tool_regex". - Name constant.ToolSearchToolRegex `json:"name,required"` + Name constant.ToolSearchToolRegex `json:"name" api:"required"` paramObj } @@ -7025,9 +7050,9 @@ const ( ) type ToolSearchToolResultBlock struct { - Content ToolSearchToolResultBlockContentUnion `json:"content,required"` - ToolUseID string `json:"tool_use_id,required"` - Type constant.ToolSearchToolResult `json:"type,required"` + Content ToolSearchToolResultBlockContentUnion `json:"content" api:"required"` + ToolUseID string `json:"tool_use_id" api:"required"` + Type constant.ToolSearchToolResult `json:"type" api:"required"` // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. JSON struct { Content respjson.Field @@ -7084,13 +7109,13 @@ func (r *ToolSearchToolResultBlockContentUnion) UnmarshalJSON(data []byte) error // The properties Content, ToolUseID, Type are required. type ToolSearchToolResultBlockParam struct { - Content ToolSearchToolResultBlockParamContentUnion `json:"content,omitzero,required"` - ToolUseID string `json:"tool_use_id,required"` + Content ToolSearchToolResultBlockParamContentUnion `json:"content,omitzero" api:"required"` + ToolUseID string `json:"tool_use_id" api:"required"` // Create a cache control breakpoint at this content block. CacheControl CacheControlEphemeralParam `json:"cache_control,omitzero"` // This field can be elided, and will marshal its zero value as // "tool_search_tool_result". - Type constant.ToolSearchToolResult `json:"type,required"` + Type constant.ToolSearchToolResult `json:"type" api:"required"` paramObj } @@ -7156,9 +7181,9 @@ func (u ToolSearchToolResultBlockParamContentUnion) GetType() *string { type ToolSearchToolResultError struct { // Any of "invalid_tool_input", "unavailable", "too_many_requests", // "execution_time_exceeded". - ErrorCode ToolSearchToolResultErrorCode `json:"error_code,required"` - ErrorMessage string `json:"error_message,required"` - Type constant.ToolSearchToolResultError `json:"type,required"` + ErrorCode ToolSearchToolResultErrorCode `json:"error_code" api:"required"` + ErrorMessage string `json:"error_message" api:"required"` + Type constant.ToolSearchToolResultError `json:"type" api:"required"` // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. JSON struct { ErrorCode respjson.Field @@ -7188,10 +7213,10 @@ const ( type ToolSearchToolResultErrorParam struct { // Any of "invalid_tool_input", "unavailable", "too_many_requests", // "execution_time_exceeded". - ErrorCode ToolSearchToolResultErrorCode `json:"error_code,omitzero,required"` + ErrorCode ToolSearchToolResultErrorCode `json:"error_code,omitzero" api:"required"` // This field can be elided, and will marshal its zero value as // "tool_search_tool_result_error". - Type constant.ToolSearchToolResultError `json:"type,required"` + Type constant.ToolSearchToolResultError `json:"type" api:"required"` paramObj } @@ -7204,8 +7229,8 @@ func (r *ToolSearchToolResultErrorParam) UnmarshalJSON(data []byte) error { } type ToolSearchToolSearchResultBlock struct { - ToolReferences []ToolReferenceBlock `json:"tool_references,required"` - Type constant.ToolSearchToolSearchResult `json:"type,required"` + ToolReferences []ToolReferenceBlock `json:"tool_references" api:"required"` + Type constant.ToolSearchToolSearchResult `json:"type" api:"required"` // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. JSON struct { ToolReferences respjson.Field @@ -7223,10 +7248,10 @@ func (r *ToolSearchToolSearchResultBlock) UnmarshalJSON(data []byte) error { // The properties ToolReferences, Type are required. type ToolSearchToolSearchResultBlockParam struct { - ToolReferences []ToolReferenceBlockParam `json:"tool_references,omitzero,required"` + ToolReferences []ToolReferenceBlockParam `json:"tool_references,omitzero" api:"required"` // This field can be elided, and will marshal its zero value as // "tool_search_tool_search_result". - Type constant.ToolSearchToolSearchResult `json:"type,required"` + Type constant.ToolSearchToolSearchResult `json:"type" api:"required"` paramObj } @@ -7256,10 +7281,10 @@ type ToolTextEditor20250124Param struct { // // This field can be elided, and will marshal its zero value as // "str_replace_editor". - Name constant.StrReplaceEditor `json:"name,required"` + Name constant.StrReplaceEditor `json:"name" api:"required"` // This field can be elided, and will marshal its zero value as // "text_editor_20250124". - Type constant.TextEditor20250124 `json:"type,required"` + Type constant.TextEditor20250124 `json:"type" api:"required"` paramObj } @@ -7289,10 +7314,10 @@ type ToolTextEditor20250429Param struct { // // This field can be elided, and will marshal its zero value as // "str_replace_based_edit_tool". - Name constant.StrReplaceBasedEditTool `json:"name,required"` + Name constant.StrReplaceBasedEditTool `json:"name" api:"required"` // This field can be elided, and will marshal its zero value as // "text_editor_20250429". - Type constant.TextEditor20250429 `json:"type,required"` + Type constant.TextEditor20250429 `json:"type" api:"required"` paramObj } @@ -7325,10 +7350,10 @@ type ToolTextEditor20250728Param struct { // // This field can be elided, and will marshal its zero value as // "str_replace_based_edit_tool". - Name constant.StrReplaceBasedEditTool `json:"name,required"` + Name constant.StrReplaceBasedEditTool `json:"name" api:"required"` // This field can be elided, and will marshal its zero value as // "text_editor_20250728". - Type constant.TextEditor20250728 `json:"type,required"` + Type constant.TextEditor20250728 `json:"type" api:"required"` paramObj } @@ -7376,6 +7401,7 @@ type ToolUnionParam struct { OfWebFetchTool20250910 *WebFetchTool20250910Param `json:",omitzero,inline"` OfWebSearchTool20260209 *WebSearchTool20260209Param `json:",omitzero,inline"` OfWebFetchTool20260209 *WebFetchTool20260209Param `json:",omitzero,inline"` + OfWebFetchTool20260309 *WebFetchTool20260309Param `json:",omitzero,inline"` OfToolSearchToolBm25_20251119 *ToolSearchToolBm25_20251119Param `json:",omitzero,inline"` OfToolSearchToolRegex20251119 *ToolSearchToolRegex20251119Param `json:",omitzero,inline"` paramUnion @@ -7395,6 +7421,7 @@ func (u ToolUnionParam) MarshalJSON() ([]byte, error) { u.OfWebFetchTool20250910, u.OfWebSearchTool20260209, u.OfWebFetchTool20260209, + u.OfWebFetchTool20260309, u.OfToolSearchToolBm25_20251119, u.OfToolSearchToolRegex20251119) } @@ -7429,6 +7456,8 @@ func (u *ToolUnionParam) asAny() any { return u.OfWebSearchTool20260209 } else if !param.IsOmitted(u.OfWebFetchTool20260209) { return u.OfWebFetchTool20260209 + } else if !param.IsOmitted(u.OfWebFetchTool20260309) { + return u.OfWebFetchTool20260309 } else if !param.IsOmitted(u.OfToolSearchToolBm25_20251119) { return u.OfToolSearchToolBm25_20251119 } else if !param.IsOmitted(u.OfToolSearchToolRegex20251119) { @@ -7469,6 +7498,14 @@ func (u ToolUnionParam) GetMaxCharacters() *int64 { return nil } +// Returns a pointer to the underlying variant's property, if present. +func (u ToolUnionParam) GetUseCache() *bool { + if vt := u.OfWebFetchTool20260309; vt != nil && vt.UseCache.Valid() { + return &vt.UseCache.Value + } + return nil +} + // Returns a pointer to the underlying variant's property, if present. func (u ToolUnionParam) GetName() *string { if vt := u.OfTool; vt != nil { @@ -7497,6 +7534,8 @@ func (u ToolUnionParam) GetName() *string { return (*string)(&vt.Name) } else if vt := u.OfWebFetchTool20260209; vt != nil { return (*string)(&vt.Name) + } else if vt := u.OfWebFetchTool20260309; vt != nil { + return (*string)(&vt.Name) } else if vt := u.OfToolSearchToolBm25_20251119; vt != nil { return (*string)(&vt.Name) } else if vt := u.OfToolSearchToolRegex20251119; vt != nil { @@ -7533,6 +7572,8 @@ func (u ToolUnionParam) GetDeferLoading() *bool { return &vt.DeferLoading.Value } else if vt := u.OfWebFetchTool20260209; vt != nil && vt.DeferLoading.Valid() { return &vt.DeferLoading.Value + } else if vt := u.OfWebFetchTool20260309; vt != nil && vt.DeferLoading.Valid() { + return &vt.DeferLoading.Value } else if vt := u.OfToolSearchToolBm25_20251119; vt != nil && vt.DeferLoading.Valid() { return &vt.DeferLoading.Value } else if vt := u.OfToolSearchToolRegex20251119; vt != nil && vt.DeferLoading.Valid() { @@ -7569,6 +7610,8 @@ func (u ToolUnionParam) GetStrict() *bool { return &vt.Strict.Value } else if vt := u.OfWebFetchTool20260209; vt != nil && vt.Strict.Valid() { return &vt.Strict.Value + } else if vt := u.OfWebFetchTool20260309; vt != nil && vt.Strict.Valid() { + return &vt.Strict.Value } else if vt := u.OfToolSearchToolBm25_20251119; vt != nil && vt.Strict.Valid() { return &vt.Strict.Value } else if vt := u.OfToolSearchToolRegex20251119; vt != nil && vt.Strict.Valid() { @@ -7605,6 +7648,8 @@ func (u ToolUnionParam) GetType() *string { return (*string)(&vt.Type) } else if vt := u.OfWebFetchTool20260209; vt != nil { return (*string)(&vt.Type) + } else if vt := u.OfWebFetchTool20260309; vt != nil { + return (*string)(&vt.Type) } else if vt := u.OfToolSearchToolBm25_20251119; vt != nil { return (*string)(&vt.Type) } else if vt := u.OfToolSearchToolRegex20251119; vt != nil { @@ -7623,6 +7668,8 @@ func (u ToolUnionParam) GetMaxUses() *int64 { return &vt.MaxUses.Value } else if vt := u.OfWebFetchTool20260209; vt != nil && vt.MaxUses.Valid() { return &vt.MaxUses.Value + } else if vt := u.OfWebFetchTool20260309; vt != nil && vt.MaxUses.Valid() { + return &vt.MaxUses.Value } return nil } @@ -7633,6 +7680,8 @@ func (u ToolUnionParam) GetMaxContentTokens() *int64 { return &vt.MaxContentTokens.Value } else if vt := u.OfWebFetchTool20260209; vt != nil && vt.MaxContentTokens.Valid() { return &vt.MaxContentTokens.Value + } else if vt := u.OfWebFetchTool20260309; vt != nil && vt.MaxContentTokens.Valid() { + return &vt.MaxContentTokens.Value } return nil } @@ -7666,6 +7715,8 @@ func (u ToolUnionParam) GetAllowedCallers() []string { return vt.AllowedCallers } else if vt := u.OfWebFetchTool20260209; vt != nil { return vt.AllowedCallers + } else if vt := u.OfWebFetchTool20260309; vt != nil { + return vt.AllowedCallers } else if vt := u.OfToolSearchToolBm25_20251119; vt != nil { return vt.AllowedCallers } else if vt := u.OfToolSearchToolRegex20251119; vt != nil { @@ -7702,6 +7753,8 @@ func (u ToolUnionParam) GetCacheControl() *CacheControlEphemeralParam { return &vt.CacheControl } else if vt := u.OfWebFetchTool20260209; vt != nil { return &vt.CacheControl + } else if vt := u.OfWebFetchTool20260309; vt != nil { + return &vt.CacheControl } else if vt := u.OfToolSearchToolBm25_20251119; vt != nil { return &vt.CacheControl } else if vt := u.OfToolSearchToolRegex20251119; vt != nil { @@ -7740,6 +7793,8 @@ func (u ToolUnionParam) GetAllowedDomains() []string { return vt.AllowedDomains } else if vt := u.OfWebFetchTool20260209; vt != nil { return vt.AllowedDomains + } else if vt := u.OfWebFetchTool20260309; vt != nil { + return vt.AllowedDomains } return nil } @@ -7755,6 +7810,8 @@ func (u ToolUnionParam) GetBlockedDomains() []string { return vt.BlockedDomains } else if vt := u.OfWebFetchTool20260209; vt != nil { return vt.BlockedDomains + } else if vt := u.OfWebFetchTool20260309; vt != nil { + return vt.BlockedDomains } return nil } @@ -7775,16 +7832,20 @@ func (u ToolUnionParam) GetCitations() *CitationsConfigParam { return &vt.Citations } else if vt := u.OfWebFetchTool20260209; vt != nil { return &vt.Citations + } else if vt := u.OfWebFetchTool20260309; vt != nil { + return &vt.Citations } return nil } type ToolUseBlock struct { - ID string `json:"id,required"` + ID string `json:"id" api:"required"` + // Tool invocation directly from the model. + Caller ToolUseBlockCallerUnion `json:"caller" api:"required"` // necessary custom code modification - Input json.RawMessage `json:"input,required"` - Name string `json:"name,required"` - Type constant.ToolUse `json:"type,required"` + Input json.RawMessage `json:"input,required"` + Name string `json:"name" api:"required"` + Type constant.ToolUse `json:"type" api:"required"` // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. JSON struct { ID respjson.Field @@ -7876,15 +7937,15 @@ func (r *ToolUseBlockCallerUnion) UnmarshalJSON(data []byte) error { // The properties ID, Input, Name, Type are required. type ToolUseBlockParam struct { - ID string `json:"id,required"` - Input any `json:"input,omitzero,required"` - Name string `json:"name,required"` + ID string `json:"id" api:"required"` + Input any `json:"input,omitzero" api:"required"` + Name string `json:"name" api:"required"` // Create a cache control breakpoint at this content block. CacheControl CacheControlEphemeralParam `json:"cache_control,omitzero"` // Tool invocation directly from the model. Caller ToolUseBlockParamCallerUnion `json:"caller,omitzero"` // This field can be elided, and will marshal its zero value as "tool_use". - Type constant.ToolUse `json:"type,required"` + Type constant.ToolUse `json:"type" api:"required"` paramObj } @@ -7946,20 +8007,11 @@ func (u ToolUseBlockParamCallerUnion) GetToolID() *string { return nil } -func init() { - apijson.RegisterUnion[ToolUseBlockParamCallerUnion]( - "type", - apijson.Discriminator[DirectCallerParam]("direct"), - apijson.Discriminator[ServerToolCallerParam]("code_execution_20250825"), - apijson.Discriminator[ServerToolCaller20260120Param]("code_execution_20260120"), - ) -} - // The properties Type, URL are required. type URLImageSourceParam struct { - URL string `json:"url,required"` + URL string `json:"url" api:"required"` // This field can be elided, and will marshal its zero value as "url". - Type constant.URL `json:"type,required"` + Type constant.URL `json:"type" api:"required"` paramObj } @@ -7973,9 +8025,9 @@ func (r *URLImageSourceParam) UnmarshalJSON(data []byte) error { // The properties Type, URL are required. type URLPDFSourceParam struct { - URL string `json:"url,required"` + URL string `json:"url" api:"required"` // This field can be elided, and will marshal its zero value as "url". - Type constant.URL `json:"type,required"` + Type constant.URL `json:"type" api:"required"` paramObj } @@ -7989,23 +8041,23 @@ func (r *URLPDFSourceParam) UnmarshalJSON(data []byte) error { type Usage struct { // Breakdown of cached tokens by TTL - CacheCreation CacheCreation `json:"cache_creation,required"` + CacheCreation CacheCreation `json:"cache_creation" api:"required"` // The number of input tokens used to create the cache entry. - CacheCreationInputTokens int64 `json:"cache_creation_input_tokens,required"` + CacheCreationInputTokens int64 `json:"cache_creation_input_tokens" api:"required"` // The number of input tokens read from the cache. - CacheReadInputTokens int64 `json:"cache_read_input_tokens,required"` + CacheReadInputTokens int64 `json:"cache_read_input_tokens" api:"required"` // The geographic region where inference was performed for this request. - InferenceGeo string `json:"inference_geo,required"` + InferenceGeo string `json:"inference_geo" api:"required"` // The number of input tokens which were used. - InputTokens int64 `json:"input_tokens,required"` + InputTokens int64 `json:"input_tokens" api:"required"` // The number of output tokens which were used. - OutputTokens int64 `json:"output_tokens,required"` + OutputTokens int64 `json:"output_tokens" api:"required"` // The number of server tool requests. - ServerToolUse ServerToolUsage `json:"server_tool_use,required"` + ServerToolUse ServerToolUsage `json:"server_tool_use" api:"required"` // If the request used the priority, standard, or batch tier. // // Any of "standard", "priority", "batch". - ServiceTier UsageServiceTier `json:"service_tier,required"` + ServiceTier UsageServiceTier `json:"service_tier" api:"required"` // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. JSON struct { CacheCreation respjson.Field @@ -8049,7 +8101,7 @@ type UserLocationParam struct { // The [IANA timezone](https://nodatime.org/TimeZones) of the user. Timezone param.Opt[string] `json:"timezone,omitzero"` // This field can be elided, and will marshal its zero value as "approximate". - Type constant.Approximate `json:"type,required"` + Type constant.Approximate `json:"type" api:"required"` paramObj } @@ -8062,12 +8114,12 @@ func (r *UserLocationParam) UnmarshalJSON(data []byte) error { } type WebFetchBlock struct { - Content DocumentBlock `json:"content,required"` + Content DocumentBlock `json:"content" api:"required"` // ISO 8601 timestamp when the content was retrieved - RetrievedAt string `json:"retrieved_at,required"` - Type constant.WebFetchResult `json:"type,required"` + RetrievedAt string `json:"retrieved_at" api:"required"` + Type constant.WebFetchResult `json:"type" api:"required"` // Fetched content URL - URL string `json:"url,required"` + URL string `json:"url" api:"required"` // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. JSON struct { Content respjson.Field @@ -8087,13 +8139,13 @@ func (r *WebFetchBlock) UnmarshalJSON(data []byte) error { // The properties Content, Type, URL are required. type WebFetchBlockParam struct { - Content DocumentBlockParam `json:"content,omitzero,required"` + Content DocumentBlockParam `json:"content,omitzero" api:"required"` // Fetched content URL - URL string `json:"url,required"` + URL string `json:"url" api:"required"` // ISO 8601 timestamp when the content was retrieved RetrievedAt param.Opt[string] `json:"retrieved_at,omitzero"` // This field can be elided, and will marshal its zero value as "web_fetch_result". - Type constant.WebFetchResult `json:"type,required"` + Type constant.WebFetchResult `json:"type" api:"required"` paramObj } @@ -8133,10 +8185,10 @@ type WebFetchTool20250910Param struct { // This is how the tool will be called by the model and in `tool_use` blocks. // // This field can be elided, and will marshal its zero value as "web_fetch". - Name constant.WebFetch `json:"name,required"` + Name constant.WebFetch `json:"name" api:"required"` // This field can be elided, and will marshal its zero value as // "web_fetch_20250910". - Type constant.WebFetch20250910 `json:"type,required"` + Type constant.WebFetch20250910 `json:"type" api:"required"` paramObj } @@ -8176,10 +8228,10 @@ type WebFetchTool20260209Param struct { // This is how the tool will be called by the model and in `tool_use` blocks. // // This field can be elided, and will marshal its zero value as "web_fetch". - Name constant.WebFetch `json:"name,required"` + Name constant.WebFetch `json:"name" api:"required"` // This field can be elided, and will marshal its zero value as // "web_fetch_20260209". - Type constant.WebFetch20260209 `json:"type,required"` + Type constant.WebFetch20260209 `json:"type" api:"required"` paramObj } @@ -8191,12 +8243,61 @@ func (r *WebFetchTool20260209Param) UnmarshalJSON(data []byte) error { return apijson.UnmarshalRoot(data, r) } +// Web fetch tool with use_cache parameter for bypassing cached content. +// +// The properties Name, Type are required. +type WebFetchTool20260309Param struct { + // Maximum number of tokens used by including web page text content in the context. + // The limit is approximate and does not apply to binary content such as PDFs. + MaxContentTokens param.Opt[int64] `json:"max_content_tokens,omitzero"` + // Maximum number of times the tool can be used in the API request. + MaxUses param.Opt[int64] `json:"max_uses,omitzero"` + // If true, tool will not be included in initial system prompt. Only loaded when + // returned via tool_reference from tool search. + DeferLoading param.Opt[bool] `json:"defer_loading,omitzero"` + // When true, guarantees schema validation on tool names and inputs + Strict param.Opt[bool] `json:"strict,omitzero"` + // Whether to use cached content. Set to false to bypass the cache and fetch fresh + // content. Only set to false when the user explicitly requests fresh content or + // when fetching rapidly-changing sources. + UseCache param.Opt[bool] `json:"use_cache,omitzero"` + // List of domains to allow fetching from + AllowedDomains []string `json:"allowed_domains,omitzero"` + // List of domains to block fetching from + BlockedDomains []string `json:"blocked_domains,omitzero"` + // Any of "direct", "code_execution_20250825", "code_execution_20260120". + AllowedCallers []string `json:"allowed_callers,omitzero"` + // Create a cache control breakpoint at this content block. + CacheControl CacheControlEphemeralParam `json:"cache_control,omitzero"` + // Citations configuration for fetched documents. Citations are disabled by + // default. + Citations CitationsConfigParam `json:"citations,omitzero"` + // Name of the tool. + // + // This is how the tool will be called by the model and in `tool_use` blocks. + // + // This field can be elided, and will marshal its zero value as "web_fetch". + Name constant.WebFetch `json:"name" api:"required"` + // This field can be elided, and will marshal its zero value as + // "web_fetch_20260309". + Type constant.WebFetch20260309 `json:"type" api:"required"` + paramObj +} + +func (r WebFetchTool20260309Param) MarshalJSON() (data []byte, err error) { + type shadow WebFetchTool20260309Param + return param.MarshalObject(r, (*shadow)(&r)) +} +func (r *WebFetchTool20260309Param) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + type WebFetchToolResultBlock struct { // Tool invocation directly from the model. - Caller WebFetchToolResultBlockCallerUnion `json:"caller,required"` - Content WebFetchToolResultBlockContentUnion `json:"content,required"` - ToolUseID string `json:"tool_use_id,required"` - Type constant.WebFetchToolResult `json:"type,required"` + Caller WebFetchToolResultBlockCallerUnion `json:"caller" api:"required"` + Content WebFetchToolResultBlockContentUnion `json:"content" api:"required"` + ToolUseID string `json:"tool_use_id" api:"required"` + Type constant.WebFetchToolResult `json:"type" api:"required"` // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. JSON struct { Caller respjson.Field @@ -8329,15 +8430,15 @@ func (r *WebFetchToolResultBlockContentUnion) UnmarshalJSON(data []byte) error { // The properties Content, ToolUseID, Type are required. type WebFetchToolResultBlockParam struct { - Content WebFetchToolResultBlockParamContentUnion `json:"content,omitzero,required"` - ToolUseID string `json:"tool_use_id,required"` + Content WebFetchToolResultBlockParamContentUnion `json:"content,omitzero" api:"required"` + ToolUseID string `json:"tool_use_id" api:"required"` // Create a cache control breakpoint at this content block. CacheControl CacheControlEphemeralParam `json:"cache_control,omitzero"` // Tool invocation directly from the model. Caller WebFetchToolResultBlockParamCallerUnion `json:"caller,omitzero"` // This field can be elided, and will marshal its zero value as // "web_fetch_tool_result". - Type constant.WebFetchToolResult `json:"type,required"` + Type constant.WebFetchToolResult `json:"type" api:"required"` paramObj } @@ -8466,21 +8567,12 @@ func (u WebFetchToolResultBlockParamCallerUnion) GetToolID() *string { return nil } -func init() { - apijson.RegisterUnion[WebFetchToolResultBlockParamCallerUnion]( - "type", - apijson.Discriminator[DirectCallerParam]("direct"), - apijson.Discriminator[ServerToolCallerParam]("code_execution_20250825"), - apijson.Discriminator[ServerToolCaller20260120Param]("code_execution_20260120"), - ) -} - type WebFetchToolResultErrorBlock struct { // Any of "invalid_tool_input", "url_too_long", "url_not_allowed", // "url_not_accessible", "unsupported_content_type", "too_many_requests", // "max_uses_exceeded", "unavailable". - ErrorCode WebFetchToolResultErrorCode `json:"error_code,required"` - Type constant.WebFetchToolResultError `json:"type,required"` + ErrorCode WebFetchToolResultErrorCode `json:"error_code" api:"required"` + Type constant.WebFetchToolResultError `json:"type" api:"required"` // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. JSON struct { ErrorCode respjson.Field @@ -8501,10 +8593,10 @@ type WebFetchToolResultErrorBlockParam struct { // Any of "invalid_tool_input", "url_too_long", "url_not_allowed", // "url_not_accessible", "unsupported_content_type", "too_many_requests", // "max_uses_exceeded", "unavailable". - ErrorCode WebFetchToolResultErrorCode `json:"error_code,omitzero,required"` + ErrorCode WebFetchToolResultErrorCode `json:"error_code,omitzero" api:"required"` // This field can be elided, and will marshal its zero value as // "web_fetch_tool_result_error". - Type constant.WebFetchToolResultError `json:"type,required"` + Type constant.WebFetchToolResultError `json:"type" api:"required"` paramObj } @@ -8530,11 +8622,11 @@ const ( ) type WebSearchResultBlock struct { - EncryptedContent string `json:"encrypted_content,required"` - PageAge string `json:"page_age,required"` - Title string `json:"title,required"` - Type constant.WebSearchResult `json:"type,required"` - URL string `json:"url,required"` + EncryptedContent string `json:"encrypted_content" api:"required"` + PageAge string `json:"page_age" api:"required"` + Title string `json:"title" api:"required"` + Type constant.WebSearchResult `json:"type" api:"required"` + URL string `json:"url" api:"required"` // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. JSON struct { EncryptedContent respjson.Field @@ -8555,13 +8647,13 @@ func (r *WebSearchResultBlock) UnmarshalJSON(data []byte) error { // The properties EncryptedContent, Title, Type, URL are required. type WebSearchResultBlockParam struct { - EncryptedContent string `json:"encrypted_content,required"` - Title string `json:"title,required"` - URL string `json:"url,required"` + EncryptedContent string `json:"encrypted_content" api:"required"` + Title string `json:"title" api:"required"` + URL string `json:"url" api:"required"` PageAge param.Opt[string] `json:"page_age,omitzero"` // This field can be elided, and will marshal its zero value as // "web_search_result". - Type constant.WebSearchResult `json:"type,required"` + Type constant.WebSearchResult `json:"type" api:"required"` paramObj } @@ -8600,10 +8692,10 @@ type WebSearchTool20250305Param struct { // This is how the tool will be called by the model and in `tool_use` blocks. // // This field can be elided, and will marshal its zero value as "web_search". - Name constant.WebSearch `json:"name,required"` + Name constant.WebSearch `json:"name" api:"required"` // This field can be elided, and will marshal its zero value as // "web_search_20250305". - Type constant.WebSearch20250305 `json:"type,required"` + Type constant.WebSearch20250305 `json:"type" api:"required"` paramObj } @@ -8642,10 +8734,10 @@ type WebSearchTool20260209Param struct { // This is how the tool will be called by the model and in `tool_use` blocks. // // This field can be elided, and will marshal its zero value as "web_search". - Name constant.WebSearch `json:"name,required"` + Name constant.WebSearch `json:"name" api:"required"` // This field can be elided, and will marshal its zero value as // "web_search_20260209". - Type constant.WebSearch20260209 `json:"type,required"` + Type constant.WebSearch20260209 `json:"type" api:"required"` paramObj } @@ -8661,10 +8753,10 @@ func (r *WebSearchTool20260209Param) UnmarshalJSON(data []byte) error { type WebSearchToolRequestErrorParam struct { // Any of "invalid_tool_input", "unavailable", "max_uses_exceeded", // "too_many_requests", "query_too_long", "request_too_large". - ErrorCode WebSearchToolResultErrorCode `json:"error_code,omitzero,required"` + ErrorCode WebSearchToolResultErrorCode `json:"error_code,omitzero" api:"required"` // This field can be elided, and will marshal its zero value as // "web_search_tool_result_error". - Type constant.WebSearchToolResultError `json:"type,required"` + Type constant.WebSearchToolResultError `json:"type" api:"required"` paramObj } @@ -8678,10 +8770,10 @@ func (r *WebSearchToolRequestErrorParam) UnmarshalJSON(data []byte) error { type WebSearchToolResultBlock struct { // Tool invocation directly from the model. - Caller WebSearchToolResultBlockCallerUnion `json:"caller,required"` - Content WebSearchToolResultBlockContentUnion `json:"content,required"` - ToolUseID string `json:"tool_use_id,required"` - Type constant.WebSearchToolResult `json:"type,required"` + Caller WebSearchToolResultBlockCallerUnion `json:"caller" api:"required"` + Content WebSearchToolResultBlockContentUnion `json:"content" api:"required"` + ToolUseID string `json:"tool_use_id" api:"required"` + Type constant.WebSearchToolResult `json:"type" api:"required"` // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. JSON struct { Caller respjson.Field @@ -8813,15 +8905,15 @@ func (r *WebSearchToolResultBlockContentUnion) UnmarshalJSON(data []byte) error // The properties Content, ToolUseID, Type are required. type WebSearchToolResultBlockParam struct { - Content WebSearchToolResultBlockParamContentUnion `json:"content,omitzero,required"` - ToolUseID string `json:"tool_use_id,required"` + Content WebSearchToolResultBlockParamContentUnion `json:"content,omitzero" api:"required"` + ToolUseID string `json:"tool_use_id" api:"required"` // Create a cache control breakpoint at this content block. CacheControl CacheControlEphemeralParam `json:"cache_control,omitzero"` // Tool invocation directly from the model. Caller WebSearchToolResultBlockParamCallerUnion `json:"caller,omitzero"` // This field can be elided, and will marshal its zero value as // "web_search_tool_result". - Type constant.WebSearchToolResult `json:"type,required"` + Type constant.WebSearchToolResult `json:"type" api:"required"` paramObj } @@ -8883,15 +8975,6 @@ func (u WebSearchToolResultBlockParamCallerUnion) GetToolID() *string { return nil } -func init() { - apijson.RegisterUnion[WebSearchToolResultBlockParamCallerUnion]( - "type", - apijson.Discriminator[DirectCallerParam]("direct"), - apijson.Discriminator[ServerToolCallerParam]("code_execution_20250825"), - apijson.Discriminator[ServerToolCaller20260120Param]("code_execution_20260120"), - ) -} - func NewWebSearchToolRequestError(errorCode WebSearchToolResultErrorCode) WebSearchToolResultBlockParamContentUnion { var variant WebSearchToolRequestErrorParam variant.ErrorCode = errorCode @@ -8926,8 +9009,8 @@ func (u *WebSearchToolResultBlockParamContentUnion) asAny() any { type WebSearchToolResultError struct { // Any of "invalid_tool_input", "unavailable", "max_uses_exceeded", // "too_many_requests", "query_too_long", "request_too_large". - ErrorCode WebSearchToolResultErrorCode `json:"error_code,required"` - Type constant.WebSearchToolResultError `json:"type,required"` + ErrorCode WebSearchToolResultErrorCode `json:"error_code" api:"required"` + Type constant.WebSearchToolResultError `json:"type" api:"required"` // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. JSON struct { ErrorCode respjson.Field @@ -8962,7 +9045,7 @@ type MessageNewParams struct { // // Different models have different maximum values for this parameter. See // [models](https://docs.claude.com/en/docs/models-overview) for details. - MaxTokens int64 `json:"max_tokens,required"` + MaxTokens int64 `json:"max_tokens" api:"required"` // Input messages. // // Our models are trained to operate on alternating `user` and `assistant` @@ -9032,11 +9115,11 @@ type MessageNewParams struct { // the Messages API. // // There is a limit of 100,000 messages in a single request. - Messages []MessageParam `json:"messages,omitzero,required"` + Messages []MessageParam `json:"messages,omitzero" api:"required"` // The model that will complete your prompt.\n\nSee // [models](https://docs.anthropic.com/en/docs/models-overview) for additional // details and options. - Model Model `json:"model,omitzero,required"` + Model Model `json:"model,omitzero" api:"required"` // Container identifier for reuse across requests. Container param.Opt[string] `json:"container,omitzero"` // Specifies the geographic region for inference processing. If not specified, the @@ -9288,11 +9371,11 @@ type MessageCountTokensParams struct { // the Messages API. // // There is a limit of 100,000 messages in a single request. - Messages []MessageParam `json:"messages,omitzero,required"` + Messages []MessageParam `json:"messages,omitzero" api:"required"` // The model that will complete your prompt.\n\nSee // [models](https://docs.anthropic.com/en/docs/models-overview) for additional // details and options. - Model Model `json:"model,omitzero,required"` + Model Model `json:"model,omitzero" api:"required"` // Top-level cache control automatically applies a cache_control marker to the last // cacheable block in the request. CacheControl CacheControlEphemeralParam `json:"cache_control,omitzero"` diff --git a/message_test.go b/message_test.go index 9062a015..288b1352 100644 --- a/message_test.go +++ b/message_test.go @@ -86,8 +86,8 @@ func TestMessageNewWithOptionalParams(t *testing.T) { }}, Temperature: anthropic.Float(1), Thinking: anthropic.ThinkingConfigParamUnion{ - OfEnabled: &anthropic.ThinkingConfigEnabledParam{ - BudgetTokens: 1024, + OfAdaptive: &anthropic.ThinkingConfigAdaptiveParam{ + Display: anthropic.ThinkingConfigAdaptiveDisplaySummarized, }, }, ToolChoice: anthropic.ToolChoiceUnionParam{ @@ -194,8 +194,8 @@ func TestMessageCountTokensWithOptionalParams(t *testing.T) { }}, }, Thinking: anthropic.ThinkingConfigParamUnion{ - OfEnabled: &anthropic.ThinkingConfigEnabledParam{ - BudgetTokens: 1024, + OfAdaptive: &anthropic.ThinkingConfigAdaptiveParam{ + Display: anthropic.ThinkingConfigAdaptiveDisplaySummarized, }, }, ToolChoice: anthropic.ToolChoiceUnionParam{ diff --git a/messagebatch.go b/messagebatch.go index d58b659a..41897808 100644 --- a/messagebatch.go +++ b/messagebatch.go @@ -55,7 +55,7 @@ func (r *MessageBatchService) New(ctx context.Context, body MessageBatchNewParam opts = slices.Concat(r.Options, opts) path := "v1/messages/batches" err = requestconfig.ExecuteNewRequest(ctx, http.MethodPost, path, body, &res, opts...) - return + return res, err } // This endpoint is idempotent and can be used to poll for Message Batch @@ -68,11 +68,11 @@ func (r *MessageBatchService) Get(ctx context.Context, messageBatchID string, op opts = slices.Concat(r.Options, opts) if messageBatchID == "" { err = errors.New("missing required message_batch_id parameter") - return + return nil, err } path := fmt.Sprintf("v1/messages/batches/%s", messageBatchID) err = requestconfig.ExecuteNewRequest(ctx, http.MethodGet, path, nil, &res, opts...) - return + return res, err } // List all Message Batches within a Workspace. Most recently created batches are @@ -117,11 +117,11 @@ func (r *MessageBatchService) Delete(ctx context.Context, messageBatchID string, opts = slices.Concat(r.Options, opts) if messageBatchID == "" { err = errors.New("missing required message_batch_id parameter") - return + return nil, err } path := fmt.Sprintf("v1/messages/batches/%s", messageBatchID) err = requestconfig.ExecuteNewRequest(ctx, http.MethodDelete, path, nil, &res, opts...) - return + return res, err } // Batches may be canceled any time before processing ends. Once cancellation is @@ -140,11 +140,11 @@ func (r *MessageBatchService) Cancel(ctx context.Context, messageBatchID string, opts = slices.Concat(r.Options, opts) if messageBatchID == "" { err = errors.New("missing required message_batch_id parameter") - return + return nil, err } path := fmt.Sprintf("v1/messages/batches/%s/cancel", messageBatchID) err = requestconfig.ExecuteNewRequest(ctx, http.MethodPost, path, nil, &res, opts...) - return + return res, err } // Streams the results of a Message Batch as a `.jsonl` file. @@ -164,7 +164,7 @@ func (r *MessageBatchService) ResultsStreaming(ctx context.Context, messageBatch opts = append([]option.RequestOption{option.WithHeader("Accept", "application/x-jsonl")}, opts...) if messageBatchID == "" { err = errors.New("missing required message_batch_id parameter") - return + return jsonl.NewStream[MessageBatchIndividualResponse](nil, err) } path := fmt.Sprintf("v1/messages/batches/%s/results", messageBatchID) err = requestconfig.ExecuteNewRequest(ctx, http.MethodGet, path, nil, &raw, opts...) @@ -173,11 +173,11 @@ func (r *MessageBatchService) ResultsStreaming(ctx context.Context, messageBatch type DeletedMessageBatch struct { // ID of the Message Batch. - ID string `json:"id,required"` + ID string `json:"id" api:"required"` // Deleted object type. // // For Message Batches, this is always `"message_batch_deleted"`. - Type constant.MessageBatchDeleted `json:"type,required"` + Type constant.MessageBatchDeleted `json:"type" api:"required"` // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. JSON struct { ID respjson.Field @@ -197,45 +197,45 @@ type MessageBatch struct { // Unique object identifier. // // The format and length of IDs may change over time. - ID string `json:"id,required"` + ID string `json:"id" api:"required"` // RFC 3339 datetime string representing the time at which the Message Batch was // archived and its results became unavailable. - ArchivedAt time.Time `json:"archived_at,required" format:"date-time"` + ArchivedAt time.Time `json:"archived_at" api:"required" format:"date-time"` // RFC 3339 datetime string representing the time at which cancellation was // initiated for the Message Batch. Specified only if cancellation was initiated. - CancelInitiatedAt time.Time `json:"cancel_initiated_at,required" format:"date-time"` + CancelInitiatedAt time.Time `json:"cancel_initiated_at" api:"required" format:"date-time"` // RFC 3339 datetime string representing the time at which the Message Batch was // created. - CreatedAt time.Time `json:"created_at,required" format:"date-time"` + CreatedAt time.Time `json:"created_at" api:"required" format:"date-time"` // RFC 3339 datetime string representing the time at which processing for the // Message Batch ended. Specified only once processing ends. // // Processing ends when every request in a Message Batch has either succeeded, // errored, canceled, or expired. - EndedAt time.Time `json:"ended_at,required" format:"date-time"` + EndedAt time.Time `json:"ended_at" api:"required" format:"date-time"` // RFC 3339 datetime string representing the time at which the Message Batch will // expire and end processing, which is 24 hours after creation. - ExpiresAt time.Time `json:"expires_at,required" format:"date-time"` + ExpiresAt time.Time `json:"expires_at" api:"required" format:"date-time"` // Processing status of the Message Batch. // // Any of "in_progress", "canceling", "ended". - ProcessingStatus MessageBatchProcessingStatus `json:"processing_status,required"` + ProcessingStatus MessageBatchProcessingStatus `json:"processing_status" api:"required"` // Tallies requests within the Message Batch, categorized by their status. // // Requests start as `processing` and move to one of the other statuses only once // processing of the entire batch ends. The sum of all values always matches the // total number of requests in the batch. - RequestCounts MessageBatchRequestCounts `json:"request_counts,required"` + RequestCounts MessageBatchRequestCounts `json:"request_counts" api:"required"` // URL to a `.jsonl` file containing the results of the Message Batch requests. // Specified only once processing ends. // // Results in the file are not guaranteed to be in the same order as requests. Use // the `custom_id` field to match results to requests. - ResultsURL string `json:"results_url,required"` + ResultsURL string `json:"results_url" api:"required"` // Object type. // // For Message Batches, this is always `"message_batch"`. - Type constant.MessageBatch `json:"type,required"` + Type constant.MessageBatch `json:"type" api:"required"` // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. JSON struct { ID respjson.Field @@ -269,7 +269,7 @@ const ( ) type MessageBatchCanceledResult struct { - Type constant.Canceled `json:"type,required"` + Type constant.Canceled `json:"type" api:"required"` // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. JSON struct { Type respjson.Field @@ -285,8 +285,8 @@ func (r *MessageBatchCanceledResult) UnmarshalJSON(data []byte) error { } type MessageBatchErroredResult struct { - Error shared.ErrorResponse `json:"error,required"` - Type constant.Errored `json:"type,required"` + Error shared.ErrorResponse `json:"error" api:"required"` + Type constant.Errored `json:"type" api:"required"` // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. JSON struct { Error respjson.Field @@ -303,7 +303,7 @@ func (r *MessageBatchErroredResult) UnmarshalJSON(data []byte) error { } type MessageBatchExpiredResult struct { - Type constant.Expired `json:"type,required"` + Type constant.Expired `json:"type" api:"required"` // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. JSON struct { Type respjson.Field @@ -325,13 +325,13 @@ type MessageBatchIndividualResponse struct { // matching results to requests, as results may be given out of request order. // // Must be unique for each request within the Message Batch. - CustomID string `json:"custom_id,required"` + CustomID string `json:"custom_id" api:"required"` // Processing result for this request. // // Contains a Message output if processing was successful, an error response if // processing failed, or the reason why processing was not attempted, such as // cancellation or expiration. - Result MessageBatchResultUnion `json:"result,required"` + Result MessageBatchResultUnion `json:"result" api:"required"` // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. JSON struct { CustomID respjson.Field @@ -351,21 +351,21 @@ type MessageBatchRequestCounts struct { // Number of requests in the Message Batch that have been canceled. // // This is zero until processing of the entire Message Batch has ended. - Canceled int64 `json:"canceled,required"` + Canceled int64 `json:"canceled" api:"required"` // Number of requests in the Message Batch that encountered an error. // // This is zero until processing of the entire Message Batch has ended. - Errored int64 `json:"errored,required"` + Errored int64 `json:"errored" api:"required"` // Number of requests in the Message Batch that have expired. // // This is zero until processing of the entire Message Batch has ended. - Expired int64 `json:"expired,required"` + Expired int64 `json:"expired" api:"required"` // Number of requests in the Message Batch that are processing. - Processing int64 `json:"processing,required"` + Processing int64 `json:"processing" api:"required"` // Number of requests in the Message Batch that have completed successfully. // // This is zero until processing of the entire Message Batch has ended. - Succeeded int64 `json:"succeeded,required"` + Succeeded int64 `json:"succeeded" api:"required"` // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. JSON struct { Canceled respjson.Field @@ -470,8 +470,8 @@ func (r *MessageBatchResultUnion) UnmarshalJSON(data []byte) error { } type MessageBatchSucceededResult struct { - Message Message `json:"message,required"` - Type constant.Succeeded `json:"type,required"` + Message Message `json:"message" api:"required"` + Type constant.Succeeded `json:"type" api:"required"` // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. JSON struct { Message respjson.Field @@ -490,7 +490,7 @@ func (r *MessageBatchSucceededResult) UnmarshalJSON(data []byte) error { type MessageBatchNewParams struct { // List of requests for prompt completion. Each is an individual request to create // a Message. - Requests []MessageBatchNewParamsRequest `json:"requests,omitzero,required"` + Requests []MessageBatchNewParamsRequest `json:"requests,omitzero" api:"required"` paramObj } @@ -508,12 +508,12 @@ type MessageBatchNewParamsRequest struct { // matching results to requests, as results may be given out of request order. // // Must be unique for each request within the Message Batch. - CustomID string `json:"custom_id,required"` + CustomID string `json:"custom_id" api:"required"` // Messages API creation parameters for the individual request. // // See the [Messages API reference](https://docs.claude.com/en/api/messages) for // full documentation on available parameters. - Params MessageBatchNewParamsRequestParams `json:"params,omitzero,required"` + Params MessageBatchNewParamsRequestParams `json:"params,omitzero" api:"required"` paramObj } @@ -539,7 +539,7 @@ type MessageBatchNewParamsRequestParams struct { // // Different models have different maximum values for this parameter. See // [models](https://docs.claude.com/en/docs/models-overview) for details. - MaxTokens int64 `json:"max_tokens,required"` + MaxTokens int64 `json:"max_tokens" api:"required"` // Input messages. // // Our models are trained to operate on alternating `user` and `assistant` @@ -609,11 +609,11 @@ type MessageBatchNewParamsRequestParams struct { // the Messages API. // // There is a limit of 100,000 messages in a single request. - Messages []MessageParam `json:"messages,omitzero,required"` + Messages []MessageParam `json:"messages,omitzero" api:"required"` // The model that will complete your prompt.\n\nSee // [models](https://docs.anthropic.com/en/docs/models-overview) for additional // details and options. - Model Model `json:"model,omitzero,required"` + Model Model `json:"model,omitzero" api:"required"` // Container identifier for reuse across requests. Container param.Opt[string] `json:"container,omitzero"` // Specifies the geographic region for inference processing. If not specified, the diff --git a/messagebatch_test.go b/messagebatch_test.go index f0d609fe..d2e94ad0 100644 --- a/messagebatch_test.go +++ b/messagebatch_test.go @@ -87,8 +87,8 @@ func TestMessageBatchNew(t *testing.T) { }}, Temperature: anthropic.Float(1), Thinking: anthropic.ThinkingConfigParamUnion{ - OfEnabled: &anthropic.ThinkingConfigEnabledParam{ - BudgetTokens: 1024, + OfAdaptive: &anthropic.ThinkingConfigAdaptiveParam{ + Display: anthropic.ThinkingConfigAdaptiveDisplaySummarized, }, }, ToolChoice: anthropic.ToolChoiceUnionParam{ diff --git a/model.go b/model.go index 7552020c..8521d917 100644 --- a/model.go +++ b/model.go @@ -51,11 +51,11 @@ func (r *ModelService) Get(ctx context.Context, modelID string, query ModelGetPa opts = slices.Concat(r.Options, opts) if modelID == "" { err = errors.New("missing required model_id parameter") - return + return nil, err } path := fmt.Sprintf("v1/models/%s", modelID) err = requestconfig.ExecuteNewRequest(ctx, http.MethodGet, path, nil, &res, opts...) - return + return res, err } // List available models. @@ -92,16 +92,16 @@ func (r *ModelService) ListAutoPaging(ctx context.Context, params ModelListParam type ModelInfo struct { // Unique model identifier. - ID string `json:"id,required"` + ID string `json:"id" api:"required"` // RFC 3339 datetime string representing the time at which the model was released. // May be set to an epoch value if the release date is unknown. - CreatedAt time.Time `json:"created_at,required" format:"date-time"` + CreatedAt time.Time `json:"created_at" api:"required" format:"date-time"` // A human-readable name for the model. - DisplayName string `json:"display_name,required"` + DisplayName string `json:"display_name" api:"required"` // Object type. // // For Models, this is always `"model"`. - Type constant.Model `json:"type,required"` + Type constant.Model `json:"type" api:"required"` // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. JSON struct { ID respjson.Field diff --git a/packages/pagination/pagination.go b/packages/pagination/pagination.go index a10b517c..16a78035 100644 --- a/packages/pagination/pagination.go +++ b/packages/pagination/pagination.go @@ -21,8 +21,8 @@ type paramObj = param.APIObject type Page[T any] struct { Data []T `json:"data"` HasMore bool `json:"has_more"` - FirstID string `json:"first_id,nullable"` - LastID string `json:"last_id,nullable"` + FirstID string `json:"first_id" api:"nullable"` + LastID string `json:"last_id" api:"nullable"` // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. JSON struct { Data respjson.Field @@ -140,7 +140,7 @@ func (r *PageAutoPager[T]) Index() int { type TokenPage[T any] struct { Data []T `json:"data"` HasMore bool `json:"has_more"` - NextPage string `json:"next_page,nullable"` + NextPage string `json:"next_page" api:"nullable"` // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. JSON struct { Data respjson.Field @@ -246,7 +246,7 @@ func (r *TokenPageAutoPager[T]) Index() int { type PageCursor[T any] struct { Data []T `json:"data"` HasMore bool `json:"has_more"` - NextPage string `json:"next_page,nullable"` + NextPage string `json:"next_page" api:"nullable"` // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. JSON struct { Data respjson.Field diff --git a/packages/respjson/decoder_test.go b/packages/respjson/decoder_test.go index aaf3306a..ac7a1b47 100644 --- a/packages/respjson/decoder_test.go +++ b/packages/respjson/decoder_test.go @@ -30,7 +30,7 @@ func (r *UnionOfStringIntOrObject) UnmarshalJSON(data []byte) error { type SubFields struct { OfBool bool `json:",inline"` - Name string `json:"name,required"` + Name string `json:"name" api:"required"` JSON struct { OfBool rj.Field Name rj.Field diff --git a/scripts/mock b/scripts/mock index 0b28f6ea..38201de8 100755 --- a/scripts/mock +++ b/scripts/mock @@ -19,23 +19,34 @@ fi echo "==> Starting mock server with URL ${URL}" -# Run prism mock on the given spec +# Run steady mock on the given spec if [ "$1" == "--daemon" ]; then - npm exec --package=@stainless-api/prism-cli@5.15.0 -- prism mock "$URL" &> .prism.log & + # Pre-install the package so the download doesn't eat into the startup timeout + npm exec --package=@stdy/cli@0.19.3 -- steady --version - # Wait for server to come online + npm exec --package=@stdy/cli@0.19.3 -- steady --host 127.0.0.1 -p 4010 --validator-query-array-format=comma --validator-query-object-format=brackets "$URL" &> .stdy.log & + + # Wait for server to come online via health endpoint (max 30s) echo -n "Waiting for server" - while ! grep -q "✖ fatal\|Prism is listening" ".prism.log" ; do + attempts=0 + while ! curl --silent --fail "http://127.0.0.1:4010/_x-steady/health" >/dev/null 2>&1; do + if ! kill -0 $! 2>/dev/null; then + echo + cat .stdy.log + exit 1 + fi + attempts=$((attempts + 1)) + if [ "$attempts" -ge 300 ]; then + echo + echo "Timed out waiting for Steady server to start" + cat .stdy.log + exit 1 + fi echo -n "." sleep 0.1 done - if grep -q "✖ fatal" ".prism.log"; then - cat .prism.log - exit 1 - fi - echo else - npm exec --package=@stainless-api/prism-cli@5.15.0 -- prism mock "$URL" + npm exec --package=@stdy/cli@0.19.3 -- steady --host 127.0.0.1 -p 4010 --validator-query-array-format=comma --validator-query-object-format=brackets "$URL" fi diff --git a/scripts/test b/scripts/test index c26b1222..868e2a94 100755 --- a/scripts/test +++ b/scripts/test @@ -9,8 +9,8 @@ GREEN='\033[0;32m' YELLOW='\033[0;33m' NC='\033[0m' # No Color -function prism_is_running() { - curl --silent "http://localhost:4010" >/dev/null 2>&1 +function steady_is_running() { + curl --silent "http://127.0.0.1:4010/_x-steady/health" >/dev/null 2>&1 } kill_server_on_port() { @@ -25,7 +25,7 @@ function is_overriding_api_base_url() { [ -n "$TEST_API_BASE_URL" ] } -if ! is_overriding_api_base_url && ! prism_is_running ; then +if ! is_overriding_api_base_url && ! steady_is_running ; then # When we exit this script, make sure to kill the background mock server process trap 'kill_server_on_port 4010' EXIT @@ -36,19 +36,19 @@ fi if is_overriding_api_base_url ; then echo -e "${GREEN}✔ Running tests against ${TEST_API_BASE_URL}${NC}" echo -elif ! prism_is_running ; then - echo -e "${RED}ERROR:${NC} The test suite will not run without a mock Prism server" +elif ! steady_is_running ; then + echo -e "${RED}ERROR:${NC} The test suite will not run without a mock Steady server" echo -e "running against your OpenAPI spec." echo echo -e "To run the server, pass in the path or url of your OpenAPI" - echo -e "spec to the prism command:" + echo -e "spec to the steady command:" echo - echo -e " \$ ${YELLOW}npm exec --package=@stainless-api/prism-cli@5.15.0 -- prism mock path/to/your.openapi.yml${NC}" + echo -e " \$ ${YELLOW}npm exec --package=@stdy/cli@0.19.3 -- steady path/to/your.openapi.yml --host 127.0.0.1 -p 4010 --validator-query-array-format=comma --validator-query-object-format=brackets${NC}" echo exit 1 else - echo -e "${GREEN}✔ Mock prism server is running with your OpenAPI spec${NC}" + echo -e "${GREEN}✔ Mock steady server is running with your OpenAPI spec${NC}" echo fi diff --git a/scripts/utils/upload-artifact.sh b/scripts/utils/upload-artifact.sh new file mode 100755 index 00000000..c3005c5a --- /dev/null +++ b/scripts/utils/upload-artifact.sh @@ -0,0 +1,50 @@ +#!/usr/bin/env bash +set -exuo pipefail + +DIST_DIR="dist" +FILENAME="source.zip" + +mapfile -d '' files < <( + find . -type f \ + \( -name '*.go' -o -name 'go.mod' -o -name 'go.sum' \) \ + ! -path "./${DIST_DIR}/*" \ + -print0 +) + +if [[ ${#files[@]} -eq 0 ]]; then + echo -e "\033[31mNo Go source files found for packaging.\033[0m" + exit 1 +fi + +mkdir -p "$DIST_DIR" +rm -f "${DIST_DIR}/${FILENAME}" + +relative_files=() +for file in "${files[@]}"; do + relative_files+=("${file#./}") +done + +zip "${DIST_DIR}/${FILENAME}" "${relative_files[@]}" + +RESPONSE=$(curl -X POST "$URL?filename=$FILENAME" \ + -H "Authorization: Bearer $AUTH" \ + -H "Content-Type: application/json") + +SIGNED_URL=$(echo "$RESPONSE" | jq -r '.url') + +if [[ "$SIGNED_URL" == "null" ]]; then + echo -e "\033[31mFailed to get signed URL.\033[0m" + exit 1 +fi + +UPLOAD_RESPONSE=$(curl -v -X PUT \ + -H "Content-Type: application/zip" \ + --data-binary "@${DIST_DIR}/${FILENAME}" "$SIGNED_URL" 2>&1) + +if echo "$UPLOAD_RESPONSE" | grep -q "HTTP/[0-9.]* 200"; then + echo -e "\033[32mUploaded build to Stainless storage.\033[0m" + echo -e "\033[32mInstallation: Download and unzip: 'https://pkg.stainless.com/s/anthropic-go/$SHA'. Run 'go mod edit -replace github.com/anthropics/anthropic-sdk-go=/path/to/unzipped_directory'.\033[0m" +else + echo -e "\033[31mFailed to upload artifact.\033[0m" + exit 1 +fi diff --git a/shared/constant/constants.go b/shared/constant/constants.go index ca5ef4b7..482b6e2b 100644 --- a/shared/constant/constants.go +++ b/shared/constant/constants.go @@ -154,6 +154,7 @@ type View string // Always "view" type WebFetch string // Always "web_fetch" type WebFetch20250910 string // Always "web_fetch_20250910" type WebFetch20260209 string // Always "web_fetch_20260209" +type WebFetch20260309 string // Always "web_fetch_20260309" type WebFetchResult string // Always "web_fetch_result" type WebFetchToolResult string // Always "web_fetch_tool_result" type WebFetchToolResultError string // Always "web_fetch_tool_result_error" @@ -318,6 +319,7 @@ func (c View) Default() View { return "view" } func (c WebFetch) Default() WebFetch { return "web_fetch" } func (c WebFetch20250910) Default() WebFetch20250910 { return "web_fetch_20250910" } func (c WebFetch20260209) Default() WebFetch20260209 { return "web_fetch_20260209" } +func (c WebFetch20260309) Default() WebFetch20260309 { return "web_fetch_20260309" } func (c WebFetchResult) Default() WebFetchResult { return "web_fetch_result" } func (c WebFetchToolResult) Default() WebFetchToolResult { return "web_fetch_tool_result" } func (c WebFetchToolResultError) Default() WebFetchToolResultError { @@ -462,6 +464,7 @@ func (c View) MarshalJSON() ([]byte, error) { retur func (c WebFetch) MarshalJSON() ([]byte, error) { return marshalString(c) } func (c WebFetch20250910) MarshalJSON() ([]byte, error) { return marshalString(c) } func (c WebFetch20260209) MarshalJSON() ([]byte, error) { return marshalString(c) } +func (c WebFetch20260309) MarshalJSON() ([]byte, error) { return marshalString(c) } func (c WebFetchResult) MarshalJSON() ([]byte, error) { return marshalString(c) } func (c WebFetchToolResult) MarshalJSON() ([]byte, error) { return marshalString(c) } func (c WebFetchToolResultError) MarshalJSON() ([]byte, error) { return marshalString(c) } diff --git a/shared/shared.go b/shared/shared.go index 5b336719..5c301957 100644 --- a/shared/shared.go +++ b/shared/shared.go @@ -18,8 +18,8 @@ type paramUnion = param.APIUnion type paramObj = param.APIObject type APIErrorObject struct { - Message string `json:"message,required"` - Type constant.APIError `json:"type,required"` + Message string `json:"message" api:"required"` + Type constant.APIError `json:"type" api:"required"` // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. JSON struct { Message respjson.Field @@ -38,8 +38,8 @@ func (r *APIErrorObject) UnmarshalJSON(data []byte) error { func (APIErrorObject) ImplErrorObjectUnion() {} type AuthenticationError struct { - Message string `json:"message,required"` - Type constant.AuthenticationError `json:"type,required"` + Message string `json:"message" api:"required"` + Type constant.AuthenticationError `json:"type" api:"required"` // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. JSON struct { Message respjson.Field @@ -58,8 +58,8 @@ func (r *AuthenticationError) UnmarshalJSON(data []byte) error { func (AuthenticationError) ImplErrorObjectUnion() {} type BillingError struct { - Message string `json:"message,required"` - Type constant.BillingError `json:"type,required"` + Message string `json:"message" api:"required"` + Type constant.BillingError `json:"type" api:"required"` // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. JSON struct { Message respjson.Field @@ -196,9 +196,9 @@ func (r *ErrorObjectUnion) UnmarshalJSON(data []byte) error { } type ErrorResponse struct { - Error ErrorObjectUnion `json:"error,required"` - RequestID string `json:"request_id,required"` - Type constant.Error `json:"type,required"` + Error ErrorObjectUnion `json:"error" api:"required"` + RequestID string `json:"request_id" api:"required"` + Type constant.Error `json:"type" api:"required"` // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. JSON struct { Error respjson.Field @@ -216,8 +216,8 @@ func (r *ErrorResponse) UnmarshalJSON(data []byte) error { } type GatewayTimeoutError struct { - Message string `json:"message,required"` - Type constant.TimeoutError `json:"type,required"` + Message string `json:"message" api:"required"` + Type constant.TimeoutError `json:"type" api:"required"` // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. JSON struct { Message respjson.Field @@ -236,8 +236,8 @@ func (r *GatewayTimeoutError) UnmarshalJSON(data []byte) error { func (GatewayTimeoutError) ImplErrorObjectUnion() {} type InvalidRequestError struct { - Message string `json:"message,required"` - Type constant.InvalidRequestError `json:"type,required"` + Message string `json:"message" api:"required"` + Type constant.InvalidRequestError `json:"type" api:"required"` // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. JSON struct { Message respjson.Field @@ -256,8 +256,8 @@ func (r *InvalidRequestError) UnmarshalJSON(data []byte) error { func (InvalidRequestError) ImplErrorObjectUnion() {} type NotFoundError struct { - Message string `json:"message,required"` - Type constant.NotFoundError `json:"type,required"` + Message string `json:"message" api:"required"` + Type constant.NotFoundError `json:"type" api:"required"` // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. JSON struct { Message respjson.Field @@ -276,8 +276,8 @@ func (r *NotFoundError) UnmarshalJSON(data []byte) error { func (NotFoundError) ImplErrorObjectUnion() {} type OverloadedError struct { - Message string `json:"message,required"` - Type constant.OverloadedError `json:"type,required"` + Message string `json:"message" api:"required"` + Type constant.OverloadedError `json:"type" api:"required"` // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. JSON struct { Message respjson.Field @@ -296,8 +296,8 @@ func (r *OverloadedError) UnmarshalJSON(data []byte) error { func (OverloadedError) ImplErrorObjectUnion() {} type PermissionError struct { - Message string `json:"message,required"` - Type constant.PermissionError `json:"type,required"` + Message string `json:"message" api:"required"` + Type constant.PermissionError `json:"type" api:"required"` // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. JSON struct { Message respjson.Field @@ -316,8 +316,8 @@ func (r *PermissionError) UnmarshalJSON(data []byte) error { func (PermissionError) ImplErrorObjectUnion() {} type RateLimitError struct { - Message string `json:"message,required"` - Type constant.RateLimitError `json:"type,required"` + Message string `json:"message" api:"required"` + Type constant.RateLimitError `json:"type" api:"required"` // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. JSON struct { Message respjson.Field diff --git a/toolrunner/runner_test.go b/toolrunner/runner_test.go index 8224b43e..399051f2 100644 --- a/toolrunner/runner_test.go +++ b/toolrunner/runner_test.go @@ -86,7 +86,7 @@ func TestToolRunner_All_Basic(t *testing.T) { runner := client.Beta.Messages.NewToolRunner([]anthropic.BetaTool{tool}, anthropic.BetaToolRunnerParams{ BetaMessageNewParams: anthropic.BetaMessageNewParams{ - Model: anthropic.ModelClaude3_7SonnetLatest, + Model: anthropic.ModelClaudeSonnet4_5, MaxTokens: 512, Messages: []anthropic.BetaMessageParam{ anthropic.NewBetaUserMessage(anthropic.NewBetaTextBlock("What's the weather in San Francisco? Use fahrenheit.")), @@ -119,7 +119,7 @@ func TestToolRunner_RunToCompletion(t *testing.T) { runner := client.Beta.Messages.NewToolRunner([]anthropic.BetaTool{tool}, anthropic.BetaToolRunnerParams{ BetaMessageNewParams: anthropic.BetaMessageNewParams{ - Model: anthropic.ModelClaude3_7SonnetLatest, + Model: anthropic.ModelClaudeSonnet4_5, MaxTokens: 512, Messages: []anthropic.BetaMessageParam{ anthropic.NewBetaUserMessage(anthropic.NewBetaTextBlock("What's the weather in San Francisco? Use fahrenheit.")), @@ -148,7 +148,7 @@ func TestToolRunner_NextMessage_Step(t *testing.T) { runner := client.Beta.Messages.NewToolRunner([]anthropic.BetaTool{tool}, anthropic.BetaToolRunnerParams{ BetaMessageNewParams: anthropic.BetaMessageNewParams{ - Model: anthropic.ModelClaude3_7SonnetLatest, + Model: anthropic.ModelClaudeSonnet4_5, MaxTokens: 512, Messages: []anthropic.BetaMessageParam{ anthropic.NewBetaUserMessage(anthropic.NewBetaTextBlock("What's the weather in SF? Use celsius.")), @@ -191,7 +191,7 @@ func TestToolRunner_AllStreaming(t *testing.T) { runner := client.Beta.Messages.NewToolRunnerStreaming([]anthropic.BetaTool{tool}, anthropic.BetaToolRunnerParams{ BetaMessageNewParams: anthropic.BetaMessageNewParams{ - Model: anthropic.ModelClaude3_7SonnetLatest, + Model: anthropic.ModelClaudeSonnet4_5, MaxTokens: 512, Messages: []anthropic.BetaMessageParam{ anthropic.NewBetaUserMessage(anthropic.NewBetaTextBlock("Weather in SF in fahrenheit?")), @@ -232,7 +232,7 @@ func TestToolRunner_NextStreaming_EventTypes(t *testing.T) { runner := client.Beta.Messages.NewToolRunnerStreaming([]anthropic.BetaTool{tool}, anthropic.BetaToolRunnerParams{ BetaMessageNewParams: anthropic.BetaMessageNewParams{ - Model: anthropic.ModelClaude3_7SonnetLatest, + Model: anthropic.ModelClaudeSonnet4_5, MaxTokens: 512, Messages: []anthropic.BetaMessageParam{ anthropic.NewBetaUserMessage(anthropic.NewBetaTextBlock("Weather in SF?")), @@ -275,7 +275,7 @@ func TestToolRunner_ToolCallError_ThenSuccess(t *testing.T) { runner := client.Beta.Messages.NewToolRunner([]anthropic.BetaTool{tool}, anthropic.BetaToolRunnerParams{ BetaMessageNewParams: anthropic.BetaMessageNewParams{ - Model: anthropic.ModelClaude3_7SonnetLatest, + Model: anthropic.ModelClaudeSonnet4_5, MaxTokens: 512, Messages: []anthropic.BetaMessageParam{ anthropic.NewBetaUserMessage(anthropic.NewBetaTextBlock("Weather in San Francisco?")), @@ -344,7 +344,7 @@ func TestToolRunner_CustomHandlingWithPushMessages(t *testing.T) { runner := client.Beta.Messages.NewToolRunner([]anthropic.BetaTool{tool}, anthropic.BetaToolRunnerParams{ BetaMessageNewParams: anthropic.BetaMessageNewParams{ - Model: anthropic.ModelClaude3_7SonnetLatest, + Model: anthropic.ModelClaudeSonnet4_5, MaxTokens: 512, Messages: []anthropic.BetaMessageParam{ anthropic.NewBetaUserMessage(anthropic.NewBetaTextBlock("What's the weather in SF in celsius?")), @@ -379,7 +379,7 @@ func TestToolRunner_CustomHandlingWithPushMessages(t *testing.T) { // No tools so the next turn is just the assistant producing final text runner2 := client.Beta.Messages.NewToolRunner(nil, anthropic.BetaToolRunnerParams{ BetaMessageNewParams: anthropic.BetaMessageNewParams{ - Model: anthropic.ModelClaude3_7SonnetLatest, + Model: anthropic.ModelClaudeSonnet4_5, MaxTokens: 512, Messages: msgs, }, @@ -401,7 +401,7 @@ func TestToolRunner_MaxIterations(t *testing.T) { runner := client.Beta.Messages.NewToolRunner([]anthropic.BetaTool{tool}, anthropic.BetaToolRunnerParams{ BetaMessageNewParams: anthropic.BetaMessageNewParams{ - Model: anthropic.ModelClaude3_7SonnetLatest, + Model: anthropic.ModelClaudeSonnet4_5, MaxTokens: 512, Messages: []anthropic.BetaMessageParam{ anthropic.NewBetaUserMessage(anthropic.NewBetaTextBlock("Check weather in SF and NY, step by step")), @@ -452,7 +452,7 @@ func TestToolRunner_ConcurrentToolExecution(t *testing.T) { runner := client.Beta.Messages.NewToolRunner([]anthropic.BetaTool{weatherTool}, anthropic.BetaToolRunnerParams{ BetaMessageNewParams: anthropic.BetaMessageNewParams{ - Model: anthropic.ModelClaude3_7SonnetLatest, + Model: anthropic.ModelClaudeSonnet4_5, MaxTokens: 512, Messages: []anthropic.BetaMessageParam{ anthropic.NewBetaUserMessage(anthropic.NewBetaTextBlock( @@ -523,7 +523,7 @@ func TestToolRunner_ContextCancellation(t *testing.T) { runner := client.Beta.Messages.NewToolRunner([]anthropic.BetaTool{slowTool}, anthropic.BetaToolRunnerParams{ BetaMessageNewParams: anthropic.BetaMessageNewParams{ - Model: anthropic.ModelClaude3_7SonnetLatest, + Model: anthropic.ModelClaudeSonnet4_5, MaxTokens: 512, Messages: []anthropic.BetaMessageParam{ anthropic.NewBetaUserMessage(anthropic.NewBetaTextBlock("Call the slow_tool with input 'test'")),