anthropic

package module
v0.2.0-alpha.3 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Oct 22, 2024 License: MIT Imports: 19 Imported by: 40

README

Anthropic Go API Library

Go Reference

The Anthropic Go library provides convenient access to the Anthropic REST API from applications written in Go. The full API of this library can be found in api.md.

Installation

import (
	"github.com/anthropics/anthropic-sdk-go" // imported as anthropic
)

Or to pin the version:

go get -u 'github.com/anthropics/anthropic-sdk-go@v0.2.0-alpha.3'

Requirements

This library requires Go 1.18+.

Usage

The full API of this library can be found in api.md.

package main

import (
	"context"
	"fmt"

	"github.com/anthropics/anthropic-sdk-go"
	"github.com/anthropics/anthropic-sdk-go/option"
)

func main() {
	client := anthropic.NewClient(
		option.WithAPIKey("my-anthropic-api-key"), // defaults to os.LookupEnv("ANTHROPIC_API_KEY")
	)
	message, err := client.Messages.New(context.TODO(), anthropic.MessageNewParams{
		Model:     anthropic.F(anthropic.ModelClaude_3_5_Sonnet_20240620),
		MaxTokens: anthropic.F(int64(1024)),
		Messages: anthropic.F([]anthropic.MessageParam{
			anthropic.NewUserMessage(anthropic.NewTextBlock("What is a quaternion?")),
		}),
	})
	if err != nil {
		panic(err.Error())
	}
	fmt.Printf("%+v\n", message.Content)
}

Conversations
messages := []anthropic.MessageParam{
	anthropic.NewUserMessage(anthropic.NewTextBlock("What is my first name?")),
}

message, err := client.Messages.New(context.TODO(), anthropic.MessageNewParams{
	Model:     anthropic.F(anthropic.ModelClaude_3_5_Sonnet_20240620),
	Messages:  anthropic.F(messages),
	MaxTokens: anthropic.F(int64(1024)),
})

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.F(anthropic.ModelClaude_3_5_Sonnet_20240620),
	Messages:  anthropic.F(messages),
	MaxTokens: anthropic.F(int64(1024)),
})
System prompts
messages := []anthropic.MessageParam{
	anthropic.NewUserMessage(anthropic.NewTextBlock("What is my first name?")),
}

message, err := client.Messages.New(context.TODO(), anthropic.MessageNewParams{
	Model:     anthropic.F(anthropic.ModelClaude_3_5_Sonnet_20240620),
	MaxTokens: anthropic.Int(1024),
	System: anthropic.F([]anthropic.TextBlockParam{
		anthropic.NewTextBlock("Be very serious at all times."),
	}),
	Messages: anthropic.F(messages),
})
Streaming
stream := client.Messages.NewStreaming(context.TODO(), anthropic.MessageNewParams{
	Model:     anthropic.F(anthropic.ModelClaude_3_5_Sonnet_20240620),
	MaxTokens: anthropic.Int(1024),
	Messages: anthropic.F([]anthropic.MessageParam{
		anthropic.NewUserMessage(anthropic.NewTextBlock(content)),
	}),
})

message := anthropic.Message{}
for stream.Next() {
	event := stream.Current()
	message.Accumulate(event)

	switch delta := event.Delta.(type) {
	case anthropic.ContentBlockDeltaEventDelta:
		if delta.Text != "" {
		    print(delta.Text)
		}
	}
}

if stream.Err() != nil {
	panic(stream.Err())
}
Tool calling
package main

import (
	"context"
	"encoding/json"
	"fmt"

	"github.com/invopop/jsonschema"
	"github.com/anthropics/anthropic-sdk-go"
)

func main() {
	client := anthropic.NewClient()

	content := "Where is San Francisco?"

	println("[user]: " + content)

	messages := []anthropic.MessageParam{
		anthropic.NewUserMessage(anthropic.NewTextBlock(content)),
	}

	tools := []anthropic.ToolParam{
		{
			Name:        anthropic.F("get_coordinates"),
			Description: anthropic.F("Accepts a place as an address, then returns the latitude and longitude coordinates."),
			InputSchema: anthropic.F(GetCoordinatesInputSchema),
		},
	}

	for {
		message, err := client.Messages.New(context.TODO(), anthropic.MessageNewParams{
			Model:     anthropic.F(anthropic.ModelClaude_3_5_Sonnet_20240620),
			MaxTokens: anthropic.Int(1024),
			Messages:  anthropic.F(messages),
			Tools:     anthropic.F(tools),
		})

		if err != nil {
			panic(err)
		}

		print(color("[assistant]: "))
		for _, block := range message.Content {
			switch block := block.AsUnion().(type) {
			case anthropic.TextBlock:
				println(block.Text)
			case anthropic.ToolUseBlock:
				println(block.Name + ": " + string(block.Input))
			}
		}

		messages = append(messages, message.ToParam())
		toolResults := []anthropic.MessageParamContentUnion{}

		for _, block := range message.Content {
			if block.Type == anthropic.ContentBlockTypeToolUse {
				print("[user (" + block.Name + ")]: ")

				var response interface{}
				switch block.Name {
				case "get_coordinates":
					input := GetCoordinatesInput{}
					err := json.Unmarshal(block.Input, &input)
					if err != nil {
						panic(err)
					}
					response = GetCoordinates(input.Location)
				}

				b, err := json.Marshal(response)
				if err != nil {
					panic(err)
				}

				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]() interface{} {
	reflector := jsonschema.Reflector{
		AllowAdditionalProperties: false,
		DoNotReference:            true,
	}
	var v T
	return reflector.Reflect(v)
}
Request fields

All request parameters are wrapped in a generic Field type, which we use to distinguish zero values from null or omitted fields.

This prevents accidentally sending a zero value if you forget a required parameter, and enables explicitly sending null, false, '', or 0 on optional parameters. Any field not specified is not sent.

To construct fields with values, use the helpers String(), Int(), Float(), or most commonly, the generic F[T](). To send a null, use Null[T](), and to send a nonconforming value, use Raw[T](any). For example:

params := FooParams{
	Name: anthropic.F("hello"),

	// Explicitly send `"description": null`
	Description: anthropic.Null[string](),

	Point: anthropic.F(anthropic.Point{
		X: anthropic.Int(0),
		Y: anthropic.Int(1),

		// In cases where the API specifies a given type,
		// but you want to send something else, use `Raw`:
		Z: anthropic.Raw[int64](0.01), // sends a float
	}),
}
Response objects

All fields in response structs are value types (not pointers or wrappers).

If a given field is null, not present, or invalid, the corresponding field will simply be its zero value.

All response structs also include a special JSON field, containing more detailed information about each property, which you can use like so:

if res.Name == "" {
	// true if `"name"` is either not present or explicitly null
	res.JSON.Name.IsNull()

	// true if the `"name"` key was not present in the repsonse JSON at all
	res.JSON.Name.IsMissing()

	// When the API returns data that cannot be coerced to the expected type:
	if res.JSON.Name.IsInvalid() {
		raw := res.JSON.Name.Raw()

		legacyName := struct{
			First string `json:"first"`
			Last  string `json:"last"`
		}{}
		json.Unmarshal([]byte(raw), &legacyName)
		name = legacyName.First + " " + legacyName.Last
	}
}

These .JSON structs also include an Extras 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.

body := res.JSON.ExtraFields["my_unexpected_field"].Raw()
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:

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"}),
)

See the full list of request options.

Pagination

This library provides some conveniences for working with paginated list endpoints.

You can use .ListAutoPaging() methods to iterate through items across all pages:

iter := client.Beta.Messages.Batches.ListAutoPaging(context.TODO(), anthropic.BetaMessageBatchListParams{
	Limit: anthropic.F(int64(20)),
})
// Automatically fetches more pages as needed.
for iter.Next() {
	betaMessageBatch := iter.Current()
	fmt.Printf("%+v\n", betaMessageBatch)
}
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.:

page, err := client.Beta.Messages.Batches.List(context.TODO(), anthropic.BetaMessageBatchListParams{
	Limit: anthropic.F(int64(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).

To handle errors, we recommend that you use the errors.As pattern:

_, err := client.Messages.New(context.TODO(), anthropic.MessageNewParams{
	MaxTokens: anthropic.F(int64(1024)),
	Model: anthropic.F(anthropic.ModelClaude_3_5_Sonnet_20240620),
})
if err != nil {
	var apierr *anthropic.Error
	if errors.As(err, &apierr) {
		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 { ... }
}

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, the context timeout does not start over. To set a per-retry timeout, use option.WithRequestTimeout().

// 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: anthropic.F(int64(1024)),
		Messages: anthropic.F([]anthropic.MessageParam{
			anthropic.NewUserMessage(anthropic.NewTextBlock("What is a quaternion?")),
		}),
		Model: anthropic.F(anthropic.ModelClaude_3_5_Sonnet_20240620),
	},
	// This sets the per-retry timeout
	option.WithRequestTimeout(20*time.Second),
)
File uploads

Request parameters that correspond to file uploads in multipart requests are typed as param.Field[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".

The file name and content-type can 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.

We also provide a helper anthropic.FileParam(reader io.Reader, filename string, contentType string) which can be used to wrap any io.Reader with the appropriate file name and content type.

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:

// 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: anthropic.F(int64(1024)),
		Messages: anthropic.F([]anthropic.MessageParam{
			anthropic.NewUserMessage(anthropic.NewTextBlock("What is a quaternion?")),
		}),
		Model: anthropic.F(anthropic.ModelClaude_3_5_Sonnet_20240620),
	},
	option.WithMaxRetries(5),
)
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.

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]interface{}

	// 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.

params := FooNewParams{
	ID:   anthropic.F("id_xxxx"),
	Data: anthropic.F(FooNewParamsData{
		FirstName: anthropic.F("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.

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, use the bedrock request option bedrock.WithLoadDefaultConfig(…) which reads the default config.

Importing the bedrock library also globally registers a decoder for application/vnd.amazon.eventstream for streaming.

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).

Read more about Anthropic and Amazon Bedrock here.

Google Vertex AI

To use this library with Google Vertex AI, use the request option vertex.WithGoogleAuth(…) which reads the Application Default Credentials.

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", "stainless-399616"),
	)
}

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.

Semantic versioning

This package generally follows SemVer conventions, though certain backwards-incompatible changes may be released as minor versions:

  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.

We take backwards-compatibility seriously and work hard to ensure you can rely on a smooth upgrade experience.

We are keen for your feedback; please open an issue with questions, bugs, or suggestions.

Contributing

See the contributing documentation.

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func Bool

func Bool(value bool) param.Field[bool]

Bool is a param field helper which helps specify bools.

func F

func F[T any](value T) param.Field[T]

F is a param field helper used to initialize a param.Field generic struct. This helps specify null, zero values, and overrides, as well as normal values. You can read more about this in our README.

func FileParam

func FileParam(reader io.Reader, filename string, contentType string) param.Field[io.Reader]

FileParam is a param field helper which helps files with a mime content-type.

func Float

func Float(value float64) param.Field[float64]

Float is a param field helper which helps specify floats.

func Int

func Int(value int64) param.Field[int64]

Int is a param field helper which helps specify integers. This is particularly helpful when specifying integer constants for fields.

func Null

func Null[T any]() param.Field[T]

Null is a param field helper which explicitly sends null to the API.

func Raw

func Raw[T any](value any) param.Field[T]

Raw is a param field helper for specifying values for fields when the type you are looking to send is different from the type that is specified in the SDK. For example, if the type of the field is an integer, but you want to send a float, you could do that by setting the corresponding field with Raw[int](0.5).

func String

func String(value string) param.Field[string]

String is a param field helper which helps specify strings.

Types

type AnthropicBeta

type AnthropicBeta = string
const (
	AnthropicBetaMessageBatches2024_09_24 AnthropicBeta = "message-batches-2024-09-24"
	AnthropicBetaPromptCaching2024_07_31  AnthropicBeta = "prompt-caching-2024-07-31"
	AnthropicBetaComputerUse2024_10_22    AnthropicBeta = "computer-use-2024-10-22"
)

type BetaAPIError

type BetaAPIError struct {
	Message string           `json:"message,required"`
	Type    BetaAPIErrorType `json:"type,required"`
	JSON    betaAPIErrorJSON `json:"-"`
}

func (*BetaAPIError) UnmarshalJSON

func (r *BetaAPIError) UnmarshalJSON(data []byte) (err error)

type BetaAPIErrorType

type BetaAPIErrorType string
const (
	BetaAPIErrorTypeAPIError BetaAPIErrorType = "api_error"
)

func (BetaAPIErrorType) IsKnown

func (r BetaAPIErrorType) IsKnown() bool

type BetaAuthenticationError

type BetaAuthenticationError struct {
	Message string                      `json:"message,required"`
	Type    BetaAuthenticationErrorType `json:"type,required"`
	JSON    betaAuthenticationErrorJSON `json:"-"`
}

func (*BetaAuthenticationError) UnmarshalJSON

func (r *BetaAuthenticationError) UnmarshalJSON(data []byte) (err error)

type BetaAuthenticationErrorType

type BetaAuthenticationErrorType string
const (
	BetaAuthenticationErrorTypeAuthenticationError BetaAuthenticationErrorType = "authentication_error"
)

func (BetaAuthenticationErrorType) IsKnown

func (r BetaAuthenticationErrorType) IsKnown() bool

type BetaCacheControlEphemeralParam

type BetaCacheControlEphemeralParam struct {
	Type param.Field[BetaCacheControlEphemeralType] `json:"type,required"`
}

func (BetaCacheControlEphemeralParam) MarshalJSON

func (r BetaCacheControlEphemeralParam) MarshalJSON() (data []byte, err error)

type BetaCacheControlEphemeralType

type BetaCacheControlEphemeralType string
const (
	BetaCacheControlEphemeralTypeEphemeral BetaCacheControlEphemeralType = "ephemeral"
)

func (BetaCacheControlEphemeralType) IsKnown

func (r BetaCacheControlEphemeralType) IsKnown() bool

type BetaContentBlock

type BetaContentBlock struct {
	Type BetaContentBlockType `json:"type,required"`
	Text string               `json:"text"`
	ID   string               `json:"id"`
	Name string               `json:"name"`
	// This field can have the runtime type of [interface{}].
	Input interface{}          `json:"input,required"`
	JSON  betaContentBlockJSON `json:"-"`
	// contains filtered or unexported fields
}

func (BetaContentBlock) AsUnion

AsUnion returns a BetaContentBlockUnion interface which you can cast to the specific types for more type safety.

Possible runtime types of the union are BetaTextBlock, BetaToolUseBlock.

func (*BetaContentBlock) UnmarshalJSON

func (r *BetaContentBlock) UnmarshalJSON(data []byte) (err error)

type BetaContentBlockParam

type BetaContentBlockParam struct {
	CacheControl param.Field[BetaCacheControlEphemeralParam] `json:"cache_control"`
	Type         param.Field[BetaContentBlockParamType]      `json:"type,required"`
	Text         param.Field[string]                         `json:"text"`
	Source       param.Field[interface{}]                    `json:"source,required"`
	ID           param.Field[string]                         `json:"id"`
	Name         param.Field[string]                         `json:"name"`
	Input        param.Field[interface{}]                    `json:"input,required"`
	ToolUseID    param.Field[string]                         `json:"tool_use_id"`
	IsError      param.Field[bool]                           `json:"is_error"`
	Content      param.Field[interface{}]                    `json:"content,required"`
}

func (BetaContentBlockParam) MarshalJSON

func (r BetaContentBlockParam) MarshalJSON() (data []byte, err error)

type BetaContentBlockParamType

type BetaContentBlockParamType string
const (
	BetaContentBlockParamTypeText       BetaContentBlockParamType = "text"
	BetaContentBlockParamTypeImage      BetaContentBlockParamType = "image"
	BetaContentBlockParamTypeToolUse    BetaContentBlockParamType = "tool_use"
	BetaContentBlockParamTypeToolResult BetaContentBlockParamType = "tool_result"
)

func (BetaContentBlockParamType) IsKnown

func (r BetaContentBlockParamType) IsKnown() bool

type BetaContentBlockParamUnion

type BetaContentBlockParamUnion interface {
	// contains filtered or unexported methods
}

Satisfied by BetaTextBlockParam, BetaImageBlockParam, BetaToolUseBlockParam, BetaToolResultBlockParam, BetaContentBlockParam.

type BetaContentBlockType

type BetaContentBlockType string
const (
	BetaContentBlockTypeText    BetaContentBlockType = "text"
	BetaContentBlockTypeToolUse BetaContentBlockType = "tool_use"
)

func (BetaContentBlockType) IsKnown

func (r BetaContentBlockType) IsKnown() bool

type BetaContentBlockUnion

type BetaContentBlockUnion interface {
	// contains filtered or unexported methods
}

Union satisfied by BetaTextBlock or BetaToolUseBlock.

type BetaError

type BetaError struct {
	Type    BetaErrorType `json:"type,required"`
	Message string        `json:"message,required"`
	JSON    betaErrorJSON `json:"-"`
	// contains filtered or unexported fields
}

func (BetaError) AsUnion

func (r BetaError) AsUnion() BetaErrorUnion

AsUnion returns a BetaErrorUnion interface which you can cast to the specific types for more type safety.

Possible runtime types of the union are BetaInvalidRequestError, BetaAuthenticationError, BetaPermissionError, BetaNotFoundError, BetaRateLimitError, BetaAPIError, BetaOverloadedError.

func (*BetaError) UnmarshalJSON

func (r *BetaError) UnmarshalJSON(data []byte) (err error)

type BetaErrorResponse

type BetaErrorResponse struct {
	Error BetaError             `json:"error,required"`
	Type  BetaErrorResponseType `json:"type,required"`
	JSON  betaErrorResponseJSON `json:"-"`
}

func (*BetaErrorResponse) UnmarshalJSON

func (r *BetaErrorResponse) UnmarshalJSON(data []byte) (err error)

type BetaErrorResponseType

type BetaErrorResponseType string
const (
	BetaErrorResponseTypeError BetaErrorResponseType = "error"
)

func (BetaErrorResponseType) IsKnown

func (r BetaErrorResponseType) IsKnown() bool

type BetaErrorType

type BetaErrorType string
const (
	BetaErrorTypeInvalidRequestError BetaErrorType = "invalid_request_error"
	BetaErrorTypeAuthenticationError BetaErrorType = "authentication_error"
	BetaErrorTypePermissionError     BetaErrorType = "permission_error"
	BetaErrorTypeNotFoundError       BetaErrorType = "not_found_error"
	BetaErrorTypeRateLimitError      BetaErrorType = "rate_limit_error"
	BetaErrorTypeAPIError            BetaErrorType = "api_error"
	BetaErrorTypeOverloadedError     BetaErrorType = "overloaded_error"
)

func (BetaErrorType) IsKnown

func (r BetaErrorType) IsKnown() bool

type BetaErrorUnion

type BetaErrorUnion interface {
	// contains filtered or unexported methods
}

Union satisfied by BetaInvalidRequestError, BetaAuthenticationError, BetaPermissionError, BetaNotFoundError, BetaRateLimitError, BetaAPIError or BetaOverloadedError.

type BetaImageBlockParam

type BetaImageBlockParam struct {
	Source       param.Field[BetaImageBlockParamSource]      `json:"source,required"`
	Type         param.Field[BetaImageBlockParamType]        `json:"type,required"`
	CacheControl param.Field[BetaCacheControlEphemeralParam] `json:"cache_control"`
}

func (BetaImageBlockParam) MarshalJSON

func (r BetaImageBlockParam) MarshalJSON() (data []byte, err error)

type BetaImageBlockParamSource

type BetaImageBlockParamSource struct {
	Data      param.Field[string]                             `json:"data,required" format:"byte"`
	MediaType param.Field[BetaImageBlockParamSourceMediaType] `json:"media_type,required"`
	Type      param.Field[BetaImageBlockParamSourceType]      `json:"type,required"`
}

func (BetaImageBlockParamSource) MarshalJSON

func (r BetaImageBlockParamSource) MarshalJSON() (data []byte, err error)

type BetaImageBlockParamSourceMediaType

type BetaImageBlockParamSourceMediaType string
const (
	BetaImageBlockParamSourceMediaTypeImageJPEG BetaImageBlockParamSourceMediaType = "image/jpeg"
	BetaImageBlockParamSourceMediaTypeImagePNG  BetaImageBlockParamSourceMediaType = "image/png"
	BetaImageBlockParamSourceMediaTypeImageGIF  BetaImageBlockParamSourceMediaType = "image/gif"
	BetaImageBlockParamSourceMediaTypeImageWebP BetaImageBlockParamSourceMediaType = "image/webp"
)

func (BetaImageBlockParamSourceMediaType) IsKnown

type BetaImageBlockParamSourceType

type BetaImageBlockParamSourceType string
const (
	BetaImageBlockParamSourceTypeBase64 BetaImageBlockParamSourceType = "base64"
)

func (BetaImageBlockParamSourceType) IsKnown

func (r BetaImageBlockParamSourceType) IsKnown() bool

type BetaImageBlockParamType

type BetaImageBlockParamType string
const (
	BetaImageBlockParamTypeImage BetaImageBlockParamType = "image"
)

func (BetaImageBlockParamType) IsKnown

func (r BetaImageBlockParamType) IsKnown() bool

type BetaInputJSONDelta

type BetaInputJSONDelta struct {
	PartialJSON string                 `json:"partial_json,required"`
	Type        BetaInputJSONDeltaType `json:"type,required"`
	JSON        betaInputJSONDeltaJSON `json:"-"`
}

func (*BetaInputJSONDelta) UnmarshalJSON

func (r *BetaInputJSONDelta) UnmarshalJSON(data []byte) (err error)

type BetaInputJSONDeltaType

type BetaInputJSONDeltaType string
const (
	BetaInputJSONDeltaTypeInputJSONDelta BetaInputJSONDeltaType = "input_json_delta"
)

func (BetaInputJSONDeltaType) IsKnown

func (r BetaInputJSONDeltaType) IsKnown() bool

type BetaInvalidRequestError

type BetaInvalidRequestError struct {
	Message string                      `json:"message,required"`
	Type    BetaInvalidRequestErrorType `json:"type,required"`
	JSON    betaInvalidRequestErrorJSON `json:"-"`
}

func (*BetaInvalidRequestError) UnmarshalJSON

func (r *BetaInvalidRequestError) UnmarshalJSON(data []byte) (err error)

type BetaInvalidRequestErrorType

type BetaInvalidRequestErrorType string
const (
	BetaInvalidRequestErrorTypeInvalidRequestError BetaInvalidRequestErrorType = "invalid_request_error"
)

func (BetaInvalidRequestErrorType) IsKnown

func (r BetaInvalidRequestErrorType) IsKnown() bool

type BetaMessage

type BetaMessage struct {
	// Unique object identifier.
	//
	// The format and length of IDs may change over time.
	ID string `json:"id,required"`
	// Content generated by the model.
	//
	// This is an array of content blocks, each of which has a `type` that determines
	// its shape.
	//
	// Example:
	//
	// “`json
	// [{ "type": "text", "text": "Hi, I'm Claude." }]
	// “`
	//
	// If the request input `messages` ended with an `assistant` turn, then the
	// response `content` will continue directly from that last turn. You can use this
	// to constrain the model's output.
	//
	// For example, if the input `messages` were:
	//
	// “`json
	// [
	//
	//	{
	//	  "role": "user",
	//	  "content": "What's the Greek name for Sun? (A) Sol (B) Helios (C) Sun"
	//	},
	//	{ "role": "assistant", "content": "The best answer is (" }
	//
	// ]
	// “`
	//
	// Then the response `content` might be:
	//
	// “`json
	// [{ "type": "text", "text": "B)" }]
	// “`
	Content []BetaContentBlock `json:"content,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"`
	// Conversational role of the generated message.
	//
	// This will always be `"assistant"`.
	Role BetaMessageRole `json:"role,required"`
	// 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.
	StopReason BetaMessageStopReason `json:"stop_reason,required,nullable"`
	// 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,nullable"`
	// Object type.
	//
	// For Messages, this is always `"message"`.
	Type BetaMessageType `json:"type,required"`
	// Billing and rate-limit usage.
	//
	// Anthropic's API bills and rate-limits by token counts, as tokens represent the
	// underlying cost to our systems.
	//
	// Under the hood, the API transforms requests into a format suitable for the
	// model. The model's output then goes through a parsing stage before becoming an
	// API response. As a result, the token counts in `usage` will not match one-to-one
	// with the exact visible content of an API request or response.
	//
	// For example, `output_tokens` will be non-zero, even for an empty string response
	// from Claude.
	Usage BetaUsage       `json:"usage,required"`
	JSON  betaMessageJSON `json:"-"`
}

func (*BetaMessage) UnmarshalJSON

func (r *BetaMessage) UnmarshalJSON(data []byte) (err error)

type BetaMessageBatch

type BetaMessageBatch struct {
	// Unique object identifier.
	//
	// The format and length of IDs may change over time.
	ID string `json:"id,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,nullable" 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,nullable" 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"`
	// 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,nullable" 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"`
	// Processing status of the Message Batch.
	ProcessingStatus BetaMessageBatchProcessingStatus `json:"processing_status,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"`
	// 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,nullable"`
	// Object type.
	//
	// For Message Batches, this is always `"message_batch"`.
	Type BetaMessageBatchType `json:"type,required"`
	JSON betaMessageBatchJSON `json:"-"`
}

func (*BetaMessageBatch) UnmarshalJSON

func (r *BetaMessageBatch) UnmarshalJSON(data []byte) (err error)

type BetaMessageBatchCancelParams

type BetaMessageBatchCancelParams struct {
	// Optional header to specify the beta version(s) you want to use.
	Betas param.Field[[]AnthropicBeta] `header:"anthropic-beta"`
}

type BetaMessageBatchCanceledResult

type BetaMessageBatchCanceledResult struct {
	Type BetaMessageBatchCanceledResultType `json:"type,required"`
	JSON betaMessageBatchCanceledResultJSON `json:"-"`
}

func (*BetaMessageBatchCanceledResult) UnmarshalJSON

func (r *BetaMessageBatchCanceledResult) UnmarshalJSON(data []byte) (err error)

type BetaMessageBatchCanceledResultType

type BetaMessageBatchCanceledResultType string
const (
	BetaMessageBatchCanceledResultTypeCanceled BetaMessageBatchCanceledResultType = "canceled"
)

func (BetaMessageBatchCanceledResultType) IsKnown

type BetaMessageBatchErroredResult

type BetaMessageBatchErroredResult struct {
	Error BetaErrorResponse                 `json:"error,required"`
	Type  BetaMessageBatchErroredResultType `json:"type,required"`
	JSON  betaMessageBatchErroredResultJSON `json:"-"`
}

func (*BetaMessageBatchErroredResult) UnmarshalJSON

func (r *BetaMessageBatchErroredResult) UnmarshalJSON(data []byte) (err error)

type BetaMessageBatchErroredResultType

type BetaMessageBatchErroredResultType string
const (
	BetaMessageBatchErroredResultTypeErrored BetaMessageBatchErroredResultType = "errored"
)

func (BetaMessageBatchErroredResultType) IsKnown

type BetaMessageBatchExpiredResult

type BetaMessageBatchExpiredResult struct {
	Type BetaMessageBatchExpiredResultType `json:"type,required"`
	JSON betaMessageBatchExpiredResultJSON `json:"-"`
}

func (*BetaMessageBatchExpiredResult) UnmarshalJSON

func (r *BetaMessageBatchExpiredResult) UnmarshalJSON(data []byte) (err error)

type BetaMessageBatchExpiredResultType

type BetaMessageBatchExpiredResultType string
const (
	BetaMessageBatchExpiredResultTypeExpired BetaMessageBatchExpiredResultType = "expired"
)

func (BetaMessageBatchExpiredResultType) IsKnown

type BetaMessageBatchGetParams

type BetaMessageBatchGetParams struct {
	// Optional header to specify the beta version(s) you want to use.
	Betas param.Field[[]AnthropicBeta] `header:"anthropic-beta"`
}

type BetaMessageBatchIndividualResponse

type BetaMessageBatchIndividualResponse struct {
	// Developer-provided ID created for each request in a Message Batch. Useful for
	// 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"`
	// 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 BetaMessageBatchResult                 `json:"result,required"`
	JSON   betaMessageBatchIndividualResponseJSON `json:"-"`
}

func (*BetaMessageBatchIndividualResponse) UnmarshalJSON

func (r *BetaMessageBatchIndividualResponse) UnmarshalJSON(data []byte) (err error)

type BetaMessageBatchListParams

type BetaMessageBatchListParams struct {
	// ID of the object to use as a cursor for pagination. When provided, returns the
	// page of results immediately after this object.
	AfterID param.Field[string] `query:"after_id"`
	// ID of the object to use as a cursor for pagination. When provided, returns the
	// page of results immediately before this object.
	BeforeID param.Field[string] `query:"before_id"`
	// Number of items to return per page.
	//
	// Defaults to `20`. Ranges from `1` to `100`.
	Limit param.Field[int64] `query:"limit"`
	// Optional header to specify the beta version(s) you want to use.
	Betas param.Field[[]AnthropicBeta] `header:"anthropic-beta"`
}

func (BetaMessageBatchListParams) URLQuery

func (r BetaMessageBatchListParams) URLQuery() (v url.Values)

URLQuery serializes BetaMessageBatchListParams's query parameters as `url.Values`.

type BetaMessageBatchNewParams

type BetaMessageBatchNewParams struct {
	// List of requests for prompt completion. Each is an individual request to create
	// a Message.
	Requests param.Field[[]BetaMessageBatchNewParamsRequest] `json:"requests,required"`
	// Optional header to specify the beta version(s) you want to use.
	Betas param.Field[[]AnthropicBeta] `header:"anthropic-beta"`
}

func (BetaMessageBatchNewParams) MarshalJSON

func (r BetaMessageBatchNewParams) MarshalJSON() (data []byte, err error)

type BetaMessageBatchNewParamsRequest

type BetaMessageBatchNewParamsRequest struct {
	// Developer-provided ID created for each request in a Message Batch. Useful for
	// matching results to requests, as results may be given out of request order.
	//
	// Must be unique for each request within the Message Batch.
	CustomID param.Field[string] `json:"custom_id,required"`
	// Messages API creation parameters for the individual request.
	//
	// See the [Messages API reference](/en/api/messages) for full documentation on
	// available parameters.
	Params param.Field[BetaMessageBatchNewParamsRequestsParams] `json:"params,required"`
}

func (BetaMessageBatchNewParamsRequest) MarshalJSON

func (r BetaMessageBatchNewParamsRequest) MarshalJSON() (data []byte, err error)

type BetaMessageBatchNewParamsRequestsParams

type BetaMessageBatchNewParamsRequestsParams struct {
	// The maximum number of tokens to generate before stopping.
	//
	// Note that our models may stop _before_ reaching this maximum. This parameter
	// only specifies the absolute maximum number of tokens to generate.
	//
	// Different models have different maximum values for this parameter. See
	// [models](https://docs.anthropic.com/en/docs/models-overview) for details.
	MaxTokens param.Field[int64] `json:"max_tokens,required"`
	// Input messages.
	//
	// Our models are trained to operate on alternating `user` and `assistant`
	// conversational turns. When creating a new `Message`, you specify the prior
	// conversational turns with the `messages` parameter, and the model then generates
	// the next `Message` in the conversation. Consecutive `user` or `assistant` turns
	// in your request will be combined into a single turn.
	//
	// Each input message must be an object with a `role` and `content`. You can
	// specify a single `user`-role message, or you can include multiple `user` and
	// `assistant` messages.
	//
	// If the final message uses the `assistant` role, the response content will
	// continue immediately from the content in that message. This can be used to
	// constrain part of the model's response.
	//
	// Example with a single `user` message:
	//
	// “`json
	// [{ "role": "user", "content": "Hello, Claude" }]
	// “`
	//
	// Example with multiple conversational turns:
	//
	// “`json
	// [
	//
	//	{ "role": "user", "content": "Hello there." },
	//	{ "role": "assistant", "content": "Hi, I'm Claude. How can I help you?" },
	//	{ "role": "user", "content": "Can you explain LLMs in plain English?" }
	//
	// ]
	// “`
	//
	// Example with a partially-filled response from Claude:
	//
	// “`json
	// [
	//
	//	{
	//	  "role": "user",
	//	  "content": "What's the Greek name for Sun? (A) Sol (B) Helios (C) Sun"
	//	},
	//	{ "role": "assistant", "content": "The best answer is (" }
	//
	// ]
	// “`
	//
	// Each input message `content` may be either a single `string` or an array of
	// content blocks, where each block has a specific `type`. Using a `string` for
	// `content` is shorthand for an array of one content block of type `"text"`. The
	// following input messages are equivalent:
	//
	// “`json
	// { "role": "user", "content": "Hello, Claude" }
	// “`
	//
	// “`json
	// { "role": "user", "content": [{ "type": "text", "text": "Hello, Claude" }] }
	// “`
	//
	// Starting with Claude 3 models, you can also send image content blocks:
	//
	// “`json
	//
	//	{
	//	  "role": "user",
	//	  "content": [
	//	    {
	//	      "type": "image",
	//	      "source": {
	//	        "type": "base64",
	//	        "media_type": "image/jpeg",
	//	        "data": "/9j/4AAQSkZJRg..."
	//	      }
	//	    },
	//	    { "type": "text", "text": "What is in this image?" }
	//	  ]
	//	}
	//
	// “`
	//
	// We currently support the `base64` source type for images, and the `image/jpeg`,
	// `image/png`, `image/gif`, and `image/webp` media types.
	//
	// See [examples](https://docs.anthropic.com/en/api/messages-examples#vision) for
	// more input examples.
	//
	// Note that if you want to include a
	// [system prompt](https://docs.anthropic.com/en/docs/system-prompts), you can use
	// the top-level `system` parameter — there is no `"system"` role for input
	// messages in the Messages API.
	Messages param.Field[[]BetaMessageParam] `json:"messages,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 param.Field[Model] `json:"model,required"`
	// An object describing metadata about the request.
	Metadata param.Field[BetaMetadataParam] `json:"metadata"`
	// Custom text sequences that will cause the model to stop generating.
	//
	// Our models will normally stop when they have naturally completed their turn,
	// which will result in a response `stop_reason` of `"end_turn"`.
	//
	// If you want the model to stop generating when it encounters custom strings of
	// text, you can use the `stop_sequences` parameter. If the model encounters one of
	// the custom sequences, the response `stop_reason` value will be `"stop_sequence"`
	// and the response `stop_sequence` value will contain the matched stop sequence.
	StopSequences param.Field[[]string] `json:"stop_sequences"`
	// Whether to incrementally stream the response using server-sent events.
	//
	// See [streaming](https://docs.anthropic.com/en/api/messages-streaming) for
	// details.
	Stream param.Field[bool] `json:"stream"`
	// System prompt.
	//
	// A system prompt is a way of providing context and instructions to Claude, such
	// as specifying a particular goal or role. See our
	// [guide to system prompts](https://docs.anthropic.com/en/docs/system-prompts).
	System param.Field[[]BetaTextBlockParam] `json:"system"`
	// Amount of randomness injected into the response.
	//
	// Defaults to `1.0`. Ranges from `0.0` to `1.0`. Use `temperature` closer to `0.0`
	// for analytical / multiple choice, and closer to `1.0` for creative and
	// generative tasks.
	//
	// Note that even with `temperature` of `0.0`, the results will not be fully
	// deterministic.
	Temperature param.Field[float64] `json:"temperature"`
	// How the model should use the provided tools. The model can use a specific tool,
	// any available tool, or decide by itself.
	ToolChoice param.Field[BetaToolChoiceUnionParam] `json:"tool_choice"`
	// Definitions of tools that the model may use.
	//
	// If you include `tools` in your API request, the model may return `tool_use`
	// content blocks that represent the model's use of those tools. You can then run
	// those tools using the tool input generated by the model and then optionally
	// return results back to the model using `tool_result` content blocks.
	//
	// Each tool definition includes:
	//
	//   - `name`: Name of the tool.
	//   - `description`: Optional, but strongly-recommended description of the tool.
	//   - `input_schema`: [JSON schema](https://json-schema.org/) for the tool `input`
	//     shape that the model will produce in `tool_use` output content blocks.
	//
	// For example, if you defined `tools` as:
	//
	// “`json
	// [
	//
	//	{
	//	  "name": "get_stock_price",
	//	  "description": "Get the current stock price for a given ticker symbol.",
	//	  "input_schema": {
	//	    "type": "object",
	//	    "properties": {
	//	      "ticker": {
	//	        "type": "string",
	//	        "description": "The stock ticker symbol, e.g. AAPL for Apple Inc."
	//	      }
	//	    },
	//	    "required": ["ticker"]
	//	  }
	//	}
	//
	// ]
	// “`
	//
	// And then asked the model "What's the S&P 500 at today?", the model might produce
	// `tool_use` content blocks in the response like this:
	//
	// “`json
	// [
	//
	//	{
	//	  "type": "tool_use",
	//	  "id": "toolu_01D7FLrfh4GYq7yT1ULFeyMV",
	//	  "name": "get_stock_price",
	//	  "input": { "ticker": "^GSPC" }
	//	}
	//
	// ]
	// “`
	//
	// You might then run your `get_stock_price` tool with `{"ticker": "^GSPC"}` as an
	// input, and return the following back to the model in a subsequent `user`
	// message:
	//
	// “`json
	// [
	//
	//	{
	//	  "type": "tool_result",
	//	  "tool_use_id": "toolu_01D7FLrfh4GYq7yT1ULFeyMV",
	//	  "content": "259.75 USD"
	//	}
	//
	// ]
	// “`
	//
	// Tools can be used for workflows that include running client-side tools and
	// functions, or more generally whenever you want the model to produce a particular
	// JSON structure of output.
	//
	// See our [guide](https://docs.anthropic.com/en/docs/tool-use) for more details.
	Tools param.Field[[]BetaToolUnionUnionParam] `json:"tools"`
	// Only sample from the top K options for each subsequent token.
	//
	// Used to remove "long tail" low probability responses.
	// [Learn more technical details here](https://towardsdatascience.com/how-to-sample-from-language-models-682bceb97277).
	//
	// Recommended for advanced use cases only. You usually only need to use
	// `temperature`.
	TopK param.Field[int64] `json:"top_k"`
	// Use nucleus sampling.
	//
	// In nucleus sampling, we compute the cumulative distribution over all the options
	// for each subsequent token in decreasing probability order and cut it off once it
	// reaches a particular probability specified by `top_p`. You should either alter
	// `temperature` or `top_p`, but not both.
	//
	// Recommended for advanced use cases only. You usually only need to use
	// `temperature`.
	TopP param.Field[float64] `json:"top_p"`
}

Messages API creation parameters for the individual request.

See the [Messages API reference](/en/api/messages) for full documentation on available parameters.

func (BetaMessageBatchNewParamsRequestsParams) MarshalJSON

func (r BetaMessageBatchNewParamsRequestsParams) MarshalJSON() (data []byte, err error)

type BetaMessageBatchProcessingStatus

type BetaMessageBatchProcessingStatus string

Processing status of the Message Batch.

const (
	BetaMessageBatchProcessingStatusInProgress BetaMessageBatchProcessingStatus = "in_progress"
	BetaMessageBatchProcessingStatusCanceling  BetaMessageBatchProcessingStatus = "canceling"
	BetaMessageBatchProcessingStatusEnded      BetaMessageBatchProcessingStatus = "ended"
)

func (BetaMessageBatchProcessingStatus) IsKnown

type BetaMessageBatchRequestCounts

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"`
	// 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"`
	// 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"`
	// Number of requests in the Message Batch that are processing.
	Processing int64 `json:"processing,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"`
	JSON      betaMessageBatchRequestCountsJSON `json:"-"`
}

func (*BetaMessageBatchRequestCounts) UnmarshalJSON

func (r *BetaMessageBatchRequestCounts) UnmarshalJSON(data []byte) (err error)

type BetaMessageBatchResult

type BetaMessageBatchResult struct {
	Type    BetaMessageBatchResultType `json:"type,required"`
	Message BetaMessage                `json:"message"`
	Error   BetaErrorResponse          `json:"error"`
	JSON    betaMessageBatchResultJSON `json:"-"`
	// contains filtered or unexported fields
}

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.

func (BetaMessageBatchResult) AsUnion

AsUnion returns a BetaMessageBatchResultUnion interface which you can cast to the specific types for more type safety.

Possible runtime types of the union are BetaMessageBatchSucceededResult, BetaMessageBatchErroredResult, BetaMessageBatchCanceledResult, BetaMessageBatchExpiredResult.

func (*BetaMessageBatchResult) UnmarshalJSON

func (r *BetaMessageBatchResult) UnmarshalJSON(data []byte) (err error)

type BetaMessageBatchResultType

type BetaMessageBatchResultType string
const (
	BetaMessageBatchResultTypeSucceeded BetaMessageBatchResultType = "succeeded"
	BetaMessageBatchResultTypeErrored   BetaMessageBatchResultType = "errored"
	BetaMessageBatchResultTypeCanceled  BetaMessageBatchResultType = "canceled"
	BetaMessageBatchResultTypeExpired   BetaMessageBatchResultType = "expired"
)

func (BetaMessageBatchResultType) IsKnown

func (r BetaMessageBatchResultType) IsKnown() bool

type BetaMessageBatchResultUnion

type BetaMessageBatchResultUnion interface {
	// contains filtered or unexported methods
}

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.

Union satisfied by BetaMessageBatchSucceededResult, BetaMessageBatchErroredResult, BetaMessageBatchCanceledResult or BetaMessageBatchExpiredResult.

type BetaMessageBatchResultsParams

type BetaMessageBatchResultsParams struct {
	// Optional header to specify the beta version(s) you want to use.
	Betas param.Field[[]AnthropicBeta] `header:"anthropic-beta"`
}

type BetaMessageBatchService

type BetaMessageBatchService struct {
	Options []option.RequestOption
}

BetaMessageBatchService contains methods and other services that help with interacting with the anthropic API.

Note, unlike clients, this service does not read variables from the environment automatically. You should not instantiate this service directly, and instead use the NewBetaMessageBatchService method instead.

func NewBetaMessageBatchService

func NewBetaMessageBatchService(opts ...option.RequestOption) (r *BetaMessageBatchService)

NewBetaMessageBatchService generates a new service that applies the given options to each request. These options are applied after the parent client's options (if there is one), and before any request-specific options.

func (*BetaMessageBatchService) Cancel

func (r *BetaMessageBatchService) Cancel(ctx context.Context, messageBatchID string, body BetaMessageBatchCancelParams, opts ...option.RequestOption) (res *BetaMessageBatch, err error)

Batches may be canceled any time before processing ends. Once cancellation is initiated, the batch enters a `canceling` state, at which time the system may complete any in-progress, non-interruptible requests before finalizing cancellation.

The number of canceled requests is specified in `request_counts`. To determine which requests were canceled, check the individual results within the batch. Note that cancellation may not result in any canceled requests if they were non-interruptible.

func (*BetaMessageBatchService) Get

func (r *BetaMessageBatchService) Get(ctx context.Context, messageBatchID string, query BetaMessageBatchGetParams, opts ...option.RequestOption) (res *BetaMessageBatch, err error)

This endpoint is idempotent and can be used to poll for Message Batch completion. To access the results of a Message Batch, make a request to the `results_url` field in the response.

func (*BetaMessageBatchService) List

List all Message Batches within a Workspace. Most recently created batches are returned first.

func (*BetaMessageBatchService) ListAutoPaging

List all Message Batches within a Workspace. Most recently created batches are returned first.

func (*BetaMessageBatchService) New

Send a batch of Message creation requests.

The Message Batches API can be used to process multiple Messages API requests at once. Once a Message Batch is created, it begins processing immediately. Batches can take up to 24 hours to complete.

func (*BetaMessageBatchService) Results

func (r *BetaMessageBatchService) Results(ctx context.Context, messageBatchID string, query BetaMessageBatchResultsParams, opts ...option.RequestOption) (res *http.Response, err error)

Streams the results of a Message Batch as a `.jsonl` file.

Each line in the file is a JSON object containing the result of a single request in the Message Batch. Results are not guaranteed to be in the same order as requests. Use the `custom_id` field to match results to requests.

type BetaMessageBatchSucceededResult

type BetaMessageBatchSucceededResult struct {
	Message BetaMessage                         `json:"message,required"`
	Type    BetaMessageBatchSucceededResultType `json:"type,required"`
	JSON    betaMessageBatchSucceededResultJSON `json:"-"`
}

func (*BetaMessageBatchSucceededResult) UnmarshalJSON

func (r *BetaMessageBatchSucceededResult) UnmarshalJSON(data []byte) (err error)

type BetaMessageBatchSucceededResultType

type BetaMessageBatchSucceededResultType string
const (
	BetaMessageBatchSucceededResultTypeSucceeded BetaMessageBatchSucceededResultType = "succeeded"
)

func (BetaMessageBatchSucceededResultType) IsKnown

type BetaMessageBatchType

type BetaMessageBatchType string

Object type.

For Message Batches, this is always `"message_batch"`.

const (
	BetaMessageBatchTypeMessageBatch BetaMessageBatchType = "message_batch"
)

func (BetaMessageBatchType) IsKnown

func (r BetaMessageBatchType) IsKnown() bool

type BetaMessageDeltaUsage

type BetaMessageDeltaUsage struct {
	// The cumulative number of output tokens which were used.
	OutputTokens int64                     `json:"output_tokens,required"`
	JSON         betaMessageDeltaUsageJSON `json:"-"`
}

func (*BetaMessageDeltaUsage) UnmarshalJSON

func (r *BetaMessageDeltaUsage) UnmarshalJSON(data []byte) (err error)

type BetaMessageNewParams

type BetaMessageNewParams struct {
	// The maximum number of tokens to generate before stopping.
	//
	// Note that our models may stop _before_ reaching this maximum. This parameter
	// only specifies the absolute maximum number of tokens to generate.
	//
	// Different models have different maximum values for this parameter. See
	// [models](https://docs.anthropic.com/en/docs/models-overview) for details.
	MaxTokens param.Field[int64] `json:"max_tokens,required"`
	// Input messages.
	//
	// Our models are trained to operate on alternating `user` and `assistant`
	// conversational turns. When creating a new `Message`, you specify the prior
	// conversational turns with the `messages` parameter, and the model then generates
	// the next `Message` in the conversation. Consecutive `user` or `assistant` turns
	// in your request will be combined into a single turn.
	//
	// Each input message must be an object with a `role` and `content`. You can
	// specify a single `user`-role message, or you can include multiple `user` and
	// `assistant` messages.
	//
	// If the final message uses the `assistant` role, the response content will
	// continue immediately from the content in that message. This can be used to
	// constrain part of the model's response.
	//
	// Example with a single `user` message:
	//
	// “`json
	// [{ "role": "user", "content": "Hello, Claude" }]
	// “`
	//
	// Example with multiple conversational turns:
	//
	// “`json
	// [
	//
	//	{ "role": "user", "content": "Hello there." },
	//	{ "role": "assistant", "content": "Hi, I'm Claude. How can I help you?" },
	//	{ "role": "user", "content": "Can you explain LLMs in plain English?" }
	//
	// ]
	// “`
	//
	// Example with a partially-filled response from Claude:
	//
	// “`json
	// [
	//
	//	{
	//	  "role": "user",
	//	  "content": "What's the Greek name for Sun? (A) Sol (B) Helios (C) Sun"
	//	},
	//	{ "role": "assistant", "content": "The best answer is (" }
	//
	// ]
	// “`
	//
	// Each input message `content` may be either a single `string` or an array of
	// content blocks, where each block has a specific `type`. Using a `string` for
	// `content` is shorthand for an array of one content block of type `"text"`. The
	// following input messages are equivalent:
	//
	// “`json
	// { "role": "user", "content": "Hello, Claude" }
	// “`
	//
	// “`json
	// { "role": "user", "content": [{ "type": "text", "text": "Hello, Claude" }] }
	// “`
	//
	// Starting with Claude 3 models, you can also send image content blocks:
	//
	// “`json
	//
	//	{
	//	  "role": "user",
	//	  "content": [
	//	    {
	//	      "type": "image",
	//	      "source": {
	//	        "type": "base64",
	//	        "media_type": "image/jpeg",
	//	        "data": "/9j/4AAQSkZJRg..."
	//	      }
	//	    },
	//	    { "type": "text", "text": "What is in this image?" }
	//	  ]
	//	}
	//
	// “`
	//
	// We currently support the `base64` source type for images, and the `image/jpeg`,
	// `image/png`, `image/gif`, and `image/webp` media types.
	//
	// See [examples](https://docs.anthropic.com/en/api/messages-examples#vision) for
	// more input examples.
	//
	// Note that if you want to include a
	// [system prompt](https://docs.anthropic.com/en/docs/system-prompts), you can use
	// the top-level `system` parameter — there is no `"system"` role for input
	// messages in the Messages API.
	Messages param.Field[[]BetaMessageParam] `json:"messages,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 param.Field[Model] `json:"model,required"`
	// An object describing metadata about the request.
	Metadata param.Field[BetaMetadataParam] `json:"metadata"`
	// Custom text sequences that will cause the model to stop generating.
	//
	// Our models will normally stop when they have naturally completed their turn,
	// which will result in a response `stop_reason` of `"end_turn"`.
	//
	// If you want the model to stop generating when it encounters custom strings of
	// text, you can use the `stop_sequences` parameter. If the model encounters one of
	// the custom sequences, the response `stop_reason` value will be `"stop_sequence"`
	// and the response `stop_sequence` value will contain the matched stop sequence.
	StopSequences param.Field[[]string] `json:"stop_sequences"`
	// System prompt.
	//
	// A system prompt is a way of providing context and instructions to Claude, such
	// as specifying a particular goal or role. See our
	// [guide to system prompts](https://docs.anthropic.com/en/docs/system-prompts).
	System param.Field[[]BetaTextBlockParam] `json:"system"`
	// Amount of randomness injected into the response.
	//
	// Defaults to `1.0`. Ranges from `0.0` to `1.0`. Use `temperature` closer to `0.0`
	// for analytical / multiple choice, and closer to `1.0` for creative and
	// generative tasks.
	//
	// Note that even with `temperature` of `0.0`, the results will not be fully
	// deterministic.
	Temperature param.Field[float64] `json:"temperature"`
	// How the model should use the provided tools. The model can use a specific tool,
	// any available tool, or decide by itself.
	ToolChoice param.Field[BetaToolChoiceUnionParam] `json:"tool_choice"`
	// Definitions of tools that the model may use.
	//
	// If you include `tools` in your API request, the model may return `tool_use`
	// content blocks that represent the model's use of those tools. You can then run
	// those tools using the tool input generated by the model and then optionally
	// return results back to the model using `tool_result` content blocks.
	//
	// Each tool definition includes:
	//
	//   - `name`: Name of the tool.
	//   - `description`: Optional, but strongly-recommended description of the tool.
	//   - `input_schema`: [JSON schema](https://json-schema.org/) for the tool `input`
	//     shape that the model will produce in `tool_use` output content blocks.
	//
	// For example, if you defined `tools` as:
	//
	// “`json
	// [
	//
	//	{
	//	  "name": "get_stock_price",
	//	  "description": "Get the current stock price for a given ticker symbol.",
	//	  "input_schema": {
	//	    "type": "object",
	//	    "properties": {
	//	      "ticker": {
	//	        "type": "string",
	//	        "description": "The stock ticker symbol, e.g. AAPL for Apple Inc."
	//	      }
	//	    },
	//	    "required": ["ticker"]
	//	  }
	//	}
	//
	// ]
	// “`
	//
	// And then asked the model "What's the S&P 500 at today?", the model might produce
	// `tool_use` content blocks in the response like this:
	//
	// “`json
	// [
	//
	//	{
	//	  "type": "tool_use",
	//	  "id": "toolu_01D7FLrfh4GYq7yT1ULFeyMV",
	//	  "name": "get_stock_price",
	//	  "input": { "ticker": "^GSPC" }
	//	}
	//
	// ]
	// “`
	//
	// You might then run your `get_stock_price` tool with `{"ticker": "^GSPC"}` as an
	// input, and return the following back to the model in a subsequent `user`
	// message:
	//
	// “`json
	// [
	//
	//	{
	//	  "type": "tool_result",
	//	  "tool_use_id": "toolu_01D7FLrfh4GYq7yT1ULFeyMV",
	//	  "content": "259.75 USD"
	//	}
	//
	// ]
	// “`
	//
	// Tools can be used for workflows that include running client-side tools and
	// functions, or more generally whenever you want the model to produce a particular
	// JSON structure of output.
	//
	// See our [guide](https://docs.anthropic.com/en/docs/tool-use) for more details.
	Tools param.Field[[]BetaToolUnionUnionParam] `json:"tools"`
	// Only sample from the top K options for each subsequent token.
	//
	// Used to remove "long tail" low probability responses.
	// [Learn more technical details here](https://towardsdatascience.com/how-to-sample-from-language-models-682bceb97277).
	//
	// Recommended for advanced use cases only. You usually only need to use
	// `temperature`.
	TopK param.Field[int64] `json:"top_k"`
	// Use nucleus sampling.
	//
	// In nucleus sampling, we compute the cumulative distribution over all the options
	// for each subsequent token in decreasing probability order and cut it off once it
	// reaches a particular probability specified by `top_p`. You should either alter
	// `temperature` or `top_p`, but not both.
	//
	// Recommended for advanced use cases only. You usually only need to use
	// `temperature`.
	TopP param.Field[float64] `json:"top_p"`
	// Optional header to specify the beta version(s) you want to use.
	Betas param.Field[[]AnthropicBeta] `header:"anthropic-beta"`
}

func (BetaMessageNewParams) MarshalJSON

func (r BetaMessageNewParams) MarshalJSON() (data []byte, err error)

type BetaMessageParam

type BetaMessageParam struct {
	Content param.Field[[]BetaContentBlockParamUnion] `json:"content,required"`
	Role    param.Field[BetaMessageParamRole]         `json:"role,required"`
}

func (BetaMessageParam) MarshalJSON

func (r BetaMessageParam) MarshalJSON() (data []byte, err error)

type BetaMessageParamRole

type BetaMessageParamRole string
const (
	BetaMessageParamRoleUser      BetaMessageParamRole = "user"
	BetaMessageParamRoleAssistant BetaMessageParamRole = "assistant"
)

func (BetaMessageParamRole) IsKnown

func (r BetaMessageParamRole) IsKnown() bool

type BetaMessageRole

type BetaMessageRole string

Conversational role of the generated message.

This will always be `"assistant"`.

const (
	BetaMessageRoleAssistant BetaMessageRole = "assistant"
)

func (BetaMessageRole) IsKnown

func (r BetaMessageRole) IsKnown() bool

type BetaMessageService

type BetaMessageService struct {
	Options []option.RequestOption
	Batches *BetaMessageBatchService
}

BetaMessageService contains methods and other services that help with interacting with the anthropic API.

Note, unlike clients, this service does not read variables from the environment automatically. You should not instantiate this service directly, and instead use the NewBetaMessageService method instead.

func NewBetaMessageService

func NewBetaMessageService(opts ...option.RequestOption) (r *BetaMessageService)

NewBetaMessageService generates a new service that applies the given options to each request. These options are applied after the parent client's options (if there is one), and before any request-specific options.

func (*BetaMessageService) New

Send a structured list of input messages with text and/or image content, and the model will generate the next message in the conversation.

The Messages API can be used for either single queries or stateless multi-turn conversations.

Note: If you choose to set a timeout for this request, we recommend 10 minutes.

func (*BetaMessageService) NewStreaming

Send a structured list of input messages with text and/or image content, and the model will generate the next message in the conversation.

The Messages API can be used for either single queries or stateless multi-turn conversations.

Note: If you choose to set a timeout for this request, we recommend 10 minutes.

type BetaMessageStopReason

type BetaMessageStopReason string

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.

const (
	BetaMessageStopReasonEndTurn      BetaMessageStopReason = "end_turn"
	BetaMessageStopReasonMaxTokens    BetaMessageStopReason = "max_tokens"
	BetaMessageStopReasonStopSequence BetaMessageStopReason = "stop_sequence"
	BetaMessageStopReasonToolUse      BetaMessageStopReason = "tool_use"
)

func (BetaMessageStopReason) IsKnown

func (r BetaMessageStopReason) IsKnown() bool

type BetaMessageType

type BetaMessageType string

Object type.

For Messages, this is always `"message"`.

const (
	BetaMessageTypeMessage BetaMessageType = "message"
)

func (BetaMessageType) IsKnown

func (r BetaMessageType) IsKnown() bool

type BetaMetadataParam

type BetaMetadataParam struct {
	// An external identifier for the user who is associated with the request.
	//
	// This should be a uuid, hash value, or other opaque identifier. Anthropic may use
	// this id to help detect abuse. Do not include any identifying information such as
	// name, email address, or phone number.
	UserID param.Field[string] `json:"user_id"`
}

func (BetaMetadataParam) MarshalJSON

func (r BetaMetadataParam) MarshalJSON() (data []byte, err error)

type BetaNotFoundError

type BetaNotFoundError struct {
	Message string                `json:"message,required"`
	Type    BetaNotFoundErrorType `json:"type,required"`
	JSON    betaNotFoundErrorJSON `json:"-"`
}

func (*BetaNotFoundError) UnmarshalJSON

func (r *BetaNotFoundError) UnmarshalJSON(data []byte) (err error)

type BetaNotFoundErrorType

type BetaNotFoundErrorType string
const (
	BetaNotFoundErrorTypeNotFoundError BetaNotFoundErrorType = "not_found_error"
)

func (BetaNotFoundErrorType) IsKnown

func (r BetaNotFoundErrorType) IsKnown() bool

type BetaOverloadedError

type BetaOverloadedError struct {
	Message string                  `json:"message,required"`
	Type    BetaOverloadedErrorType `json:"type,required"`
	JSON    betaOverloadedErrorJSON `json:"-"`
}

func (*BetaOverloadedError) UnmarshalJSON

func (r *BetaOverloadedError) UnmarshalJSON(data []byte) (err error)

type BetaOverloadedErrorType

type BetaOverloadedErrorType string
const (
	BetaOverloadedErrorTypeOverloadedError BetaOverloadedErrorType = "overloaded_error"
)

func (BetaOverloadedErrorType) IsKnown

func (r BetaOverloadedErrorType) IsKnown() bool

type BetaPermissionError

type BetaPermissionError struct {
	Message string                  `json:"message,required"`
	Type    BetaPermissionErrorType `json:"type,required"`
	JSON    betaPermissionErrorJSON `json:"-"`
}

func (*BetaPermissionError) UnmarshalJSON

func (r *BetaPermissionError) UnmarshalJSON(data []byte) (err error)

type BetaPermissionErrorType

type BetaPermissionErrorType string
const (
	BetaPermissionErrorTypePermissionError BetaPermissionErrorType = "permission_error"
)

func (BetaPermissionErrorType) IsKnown

func (r BetaPermissionErrorType) IsKnown() bool

type BetaPromptCachingMessageNewParams

type BetaPromptCachingMessageNewParams struct {
	// The maximum number of tokens to generate before stopping.
	//
	// Note that our models may stop _before_ reaching this maximum. This parameter
	// only specifies the absolute maximum number of tokens to generate.
	//
	// Different models have different maximum values for this parameter. See
	// [models](https://docs.anthropic.com/en/docs/models-overview) for details.
	MaxTokens param.Field[int64] `json:"max_tokens,required"`
	// Input messages.
	//
	// Our models are trained to operate on alternating `user` and `assistant`
	// conversational turns. When creating a new `Message`, you specify the prior
	// conversational turns with the `messages` parameter, and the model then generates
	// the next `Message` in the conversation. Consecutive `user` or `assistant` turns
	// in your request will be combined into a single turn.
	//
	// Each input message must be an object with a `role` and `content`. You can
	// specify a single `user`-role message, or you can include multiple `user` and
	// `assistant` messages.
	//
	// If the final message uses the `assistant` role, the response content will
	// continue immediately from the content in that message. This can be used to
	// constrain part of the model's response.
	//
	// Example with a single `user` message:
	//
	// “`json
	// [{ "role": "user", "content": "Hello, Claude" }]
	// “`
	//
	// Example with multiple conversational turns:
	//
	// “`json
	// [
	//
	//	{ "role": "user", "content": "Hello there." },
	//	{ "role": "assistant", "content": "Hi, I'm Claude. How can I help you?" },
	//	{ "role": "user", "content": "Can you explain LLMs in plain English?" }
	//
	// ]
	// “`
	//
	// Example with a partially-filled response from Claude:
	//
	// “`json
	// [
	//
	//	{
	//	  "role": "user",
	//	  "content": "What's the Greek name for Sun? (A) Sol (B) Helios (C) Sun"
	//	},
	//	{ "role": "assistant", "content": "The best answer is (" }
	//
	// ]
	// “`
	//
	// Each input message `content` may be either a single `string` or an array of
	// content blocks, where each block has a specific `type`. Using a `string` for
	// `content` is shorthand for an array of one content block of type `"text"`. The
	// following input messages are equivalent:
	//
	// “`json
	// { "role": "user", "content": "Hello, Claude" }
	// “`
	//
	// “`json
	// { "role": "user", "content": [{ "type": "text", "text": "Hello, Claude" }] }
	// “`
	//
	// Starting with Claude 3 models, you can also send image content blocks:
	//
	// “`json
	//
	//	{
	//	  "role": "user",
	//	  "content": [
	//	    {
	//	      "type": "image",
	//	      "source": {
	//	        "type": "base64",
	//	        "media_type": "image/jpeg",
	//	        "data": "/9j/4AAQSkZJRg..."
	//	      }
	//	    },
	//	    { "type": "text", "text": "What is in this image?" }
	//	  ]
	//	}
	//
	// “`
	//
	// We currently support the `base64` source type for images, and the `image/jpeg`,
	// `image/png`, `image/gif`, and `image/webp` media types.
	//
	// See [examples](https://docs.anthropic.com/en/api/messages-examples#vision) for
	// more input examples.
	//
	// Note that if you want to include a
	// [system prompt](https://docs.anthropic.com/en/docs/system-prompts), you can use
	// the top-level `system` parameter — there is no `"system"` role for input
	// messages in the Messages API.
	Messages param.Field[[]PromptCachingBetaMessageParam] `json:"messages,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 param.Field[Model] `json:"model,required"`
	// An object describing metadata about the request.
	Metadata param.Field[MetadataParam] `json:"metadata"`
	// Custom text sequences that will cause the model to stop generating.
	//
	// Our models will normally stop when they have naturally completed their turn,
	// which will result in a response `stop_reason` of `"end_turn"`.
	//
	// If you want the model to stop generating when it encounters custom strings of
	// text, you can use the `stop_sequences` parameter. If the model encounters one of
	// the custom sequences, the response `stop_reason` value will be `"stop_sequence"`
	// and the response `stop_sequence` value will contain the matched stop sequence.
	StopSequences param.Field[[]string] `json:"stop_sequences"`
	// System prompt.
	//
	// A system prompt is a way of providing context and instructions to Claude, such
	// as specifying a particular goal or role. See our
	// [guide to system prompts](https://docs.anthropic.com/en/docs/system-prompts).
	System param.Field[BetaPromptCachingMessageNewParamsSystemUnion] `json:"system"`
	// Amount of randomness injected into the response.
	//
	// Defaults to `1.0`. Ranges from `0.0` to `1.0`. Use `temperature` closer to `0.0`
	// for analytical / multiple choice, and closer to `1.0` for creative and
	// generative tasks.
	//
	// Note that even with `temperature` of `0.0`, the results will not be fully
	// deterministic.
	Temperature param.Field[float64] `json:"temperature"`
	// How the model should use the provided tools. The model can use a specific tool,
	// any available tool, or decide by itself.
	ToolChoice param.Field[ToolChoiceUnionParam] `json:"tool_choice"`
	// Definitions of tools that the model may use.
	//
	// If you include `tools` in your API request, the model may return `tool_use`
	// content blocks that represent the model's use of those tools. You can then run
	// those tools using the tool input generated by the model and then optionally
	// return results back to the model using `tool_result` content blocks.
	//
	// Each tool definition includes:
	//
	//   - `name`: Name of the tool.
	//   - `description`: Optional, but strongly-recommended description of the tool.
	//   - `input_schema`: [JSON schema](https://json-schema.org/) for the tool `input`
	//     shape that the model will produce in `tool_use` output content blocks.
	//
	// For example, if you defined `tools` as:
	//
	// “`json
	// [
	//
	//	{
	//	  "name": "get_stock_price",
	//	  "description": "Get the current stock price for a given ticker symbol.",
	//	  "input_schema": {
	//	    "type": "object",
	//	    "properties": {
	//	      "ticker": {
	//	        "type": "string",
	//	        "description": "The stock ticker symbol, e.g. AAPL for Apple Inc."
	//	      }
	//	    },
	//	    "required": ["ticker"]
	//	  }
	//	}
	//
	// ]
	// “`
	//
	// And then asked the model "What's the S&P 500 at today?", the model might produce
	// `tool_use` content blocks in the response like this:
	//
	// “`json
	// [
	//
	//	{
	//	  "type": "tool_use",
	//	  "id": "toolu_01D7FLrfh4GYq7yT1ULFeyMV",
	//	  "name": "get_stock_price",
	//	  "input": { "ticker": "^GSPC" }
	//	}
	//
	// ]
	// “`
	//
	// You might then run your `get_stock_price` tool with `{"ticker": "^GSPC"}` as an
	// input, and return the following back to the model in a subsequent `user`
	// message:
	//
	// “`json
	// [
	//
	//	{
	//	  "type": "tool_result",
	//	  "tool_use_id": "toolu_01D7FLrfh4GYq7yT1ULFeyMV",
	//	  "content": "259.75 USD"
	//	}
	//
	// ]
	// “`
	//
	// Tools can be used for workflows that include running client-side tools and
	// functions, or more generally whenever you want the model to produce a particular
	// JSON structure of output.
	//
	// See our [guide](https://docs.anthropic.com/en/docs/tool-use) for more details.
	Tools param.Field[[]PromptCachingBetaToolParam] `json:"tools"`
	// Only sample from the top K options for each subsequent token.
	//
	// Used to remove "long tail" low probability responses.
	// [Learn more technical details here](https://towardsdatascience.com/how-to-sample-from-language-models-682bceb97277).
	//
	// Recommended for advanced use cases only. You usually only need to use
	// `temperature`.
	TopK param.Field[int64] `json:"top_k"`
	// Use nucleus sampling.
	//
	// In nucleus sampling, we compute the cumulative distribution over all the options
	// for each subsequent token in decreasing probability order and cut it off once it
	// reaches a particular probability specified by `top_p`. You should either alter
	// `temperature` or `top_p`, but not both.
	//
	// Recommended for advanced use cases only. You usually only need to use
	// `temperature`.
	TopP param.Field[float64] `json:"top_p"`
	// Optional header to specify the beta version(s) you want to use.
	Betas param.Field[[]AnthropicBeta] `header:"anthropic-beta"`
}

func (BetaPromptCachingMessageNewParams) MarshalJSON

func (r BetaPromptCachingMessageNewParams) MarshalJSON() (data []byte, err error)

type BetaPromptCachingMessageNewParamsSystemArray

type BetaPromptCachingMessageNewParamsSystemArray []PromptCachingBetaTextBlockParam

func (BetaPromptCachingMessageNewParamsSystemArray) ImplementsBetaPromptCachingMessageNewParamsSystemUnion

func (r BetaPromptCachingMessageNewParamsSystemArray) ImplementsBetaPromptCachingMessageNewParamsSystemUnion()

type BetaPromptCachingMessageNewParamsSystemUnion

type BetaPromptCachingMessageNewParamsSystemUnion interface {
	ImplementsBetaPromptCachingMessageNewParamsSystemUnion()
}

System prompt.

A system prompt is a way of providing context and instructions to Claude, such as specifying a particular goal or role. See our [guide to system prompts](https://docs.anthropic.com/en/docs/system-prompts).

Satisfied by [shared.UnionString], BetaPromptCachingMessageNewParamsSystemArray.

type BetaPromptCachingMessageService

type BetaPromptCachingMessageService struct {
	Options []option.RequestOption
}

BetaPromptCachingMessageService contains methods and other services that help with interacting with the anthropic API.

Note, unlike clients, this service does not read variables from the environment automatically. You should not instantiate this service directly, and instead use the NewBetaPromptCachingMessageService method instead.

func NewBetaPromptCachingMessageService

func NewBetaPromptCachingMessageService(opts ...option.RequestOption) (r *BetaPromptCachingMessageService)

NewBetaPromptCachingMessageService generates a new service that applies the given options to each request. These options are applied after the parent client's options (if there is one), and before any request-specific options.

func (*BetaPromptCachingMessageService) New

Send a structured list of input messages with text and/or image content, and the model will generate the next message in the conversation.

The Messages API can be used for either single queries or stateless multi-turn conversations.

Note: If you choose to set a timeout for this request, we recommend 10 minutes.

func (*BetaPromptCachingMessageService) NewStreaming

Send a structured list of input messages with text and/or image content, and the model will generate the next message in the conversation.

The Messages API can be used for either single queries or stateless multi-turn conversations.

Note: If you choose to set a timeout for this request, we recommend 10 minutes.

type BetaPromptCachingService

type BetaPromptCachingService struct {
	Options  []option.RequestOption
	Messages *BetaPromptCachingMessageService
}

BetaPromptCachingService contains methods and other services that help with interacting with the anthropic API.

Note, unlike clients, this service does not read variables from the environment automatically. You should not instantiate this service directly, and instead use the NewBetaPromptCachingService method instead.

func NewBetaPromptCachingService

func NewBetaPromptCachingService(opts ...option.RequestOption) (r *BetaPromptCachingService)

NewBetaPromptCachingService generates a new service that applies the given options to each request. These options are applied after the parent client's options (if there is one), and before any request-specific options.

type BetaRateLimitError

type BetaRateLimitError struct {
	Message string                 `json:"message,required"`
	Type    BetaRateLimitErrorType `json:"type,required"`
	JSON    betaRateLimitErrorJSON `json:"-"`
}

func (*BetaRateLimitError) UnmarshalJSON

func (r *BetaRateLimitError) UnmarshalJSON(data []byte) (err error)

type BetaRateLimitErrorType

type BetaRateLimitErrorType string
const (
	BetaRateLimitErrorTypeRateLimitError BetaRateLimitErrorType = "rate_limit_error"
)

func (BetaRateLimitErrorType) IsKnown

func (r BetaRateLimitErrorType) IsKnown() bool

type BetaRawContentBlockDeltaEvent

type BetaRawContentBlockDeltaEvent struct {
	Delta BetaRawContentBlockDeltaEventDelta `json:"delta,required"`
	Index int64                              `json:"index,required"`
	Type  BetaRawContentBlockDeltaEventType  `json:"type,required"`
	JSON  betaRawContentBlockDeltaEventJSON  `json:"-"`
}

func (*BetaRawContentBlockDeltaEvent) UnmarshalJSON

func (r *BetaRawContentBlockDeltaEvent) UnmarshalJSON(data []byte) (err error)

type BetaRawContentBlockDeltaEventDelta

type BetaRawContentBlockDeltaEventDelta struct {
	Type        BetaRawContentBlockDeltaEventDeltaType `json:"type,required"`
	Text        string                                 `json:"text"`
	PartialJSON string                                 `json:"partial_json"`
	JSON        betaRawContentBlockDeltaEventDeltaJSON `json:"-"`
	// contains filtered or unexported fields
}

func (BetaRawContentBlockDeltaEventDelta) AsUnion

AsUnion returns a BetaRawContentBlockDeltaEventDeltaUnion interface which you can cast to the specific types for more type safety.

Possible runtime types of the union are BetaTextDelta, BetaInputJSONDelta.

func (*BetaRawContentBlockDeltaEventDelta) UnmarshalJSON

func (r *BetaRawContentBlockDeltaEventDelta) UnmarshalJSON(data []byte) (err error)

type BetaRawContentBlockDeltaEventDeltaType

type BetaRawContentBlockDeltaEventDeltaType string
const (
	BetaRawContentBlockDeltaEventDeltaTypeTextDelta      BetaRawContentBlockDeltaEventDeltaType = "text_delta"
	BetaRawContentBlockDeltaEventDeltaTypeInputJSONDelta BetaRawContentBlockDeltaEventDeltaType = "input_json_delta"
)

func (BetaRawContentBlockDeltaEventDeltaType) IsKnown

type BetaRawContentBlockDeltaEventDeltaUnion

type BetaRawContentBlockDeltaEventDeltaUnion interface {
	// contains filtered or unexported methods
}

Union satisfied by BetaTextDelta or BetaInputJSONDelta.

type BetaRawContentBlockDeltaEventType

type BetaRawContentBlockDeltaEventType string
const (
	BetaRawContentBlockDeltaEventTypeContentBlockDelta BetaRawContentBlockDeltaEventType = "content_block_delta"
)

func (BetaRawContentBlockDeltaEventType) IsKnown

type BetaRawContentBlockStartEvent

type BetaRawContentBlockStartEvent struct {
	ContentBlock BetaRawContentBlockStartEventContentBlock `json:"content_block,required"`
	Index        int64                                     `json:"index,required"`
	Type         BetaRawContentBlockStartEventType         `json:"type,required"`
	JSON         betaRawContentBlockStartEventJSON         `json:"-"`
}

func (*BetaRawContentBlockStartEvent) UnmarshalJSON

func (r *BetaRawContentBlockStartEvent) UnmarshalJSON(data []byte) (err error)

type BetaRawContentBlockStartEventContentBlock

type BetaRawContentBlockStartEventContentBlock struct {
	Type BetaRawContentBlockStartEventContentBlockType `json:"type,required"`
	Text string                                        `json:"text"`
	ID   string                                        `json:"id"`
	Name string                                        `json:"name"`
	// This field can have the runtime type of [interface{}].
	Input interface{}                                   `json:"input,required"`
	JSON  betaRawContentBlockStartEventContentBlockJSON `json:"-"`
	// contains filtered or unexported fields
}

func (BetaRawContentBlockStartEventContentBlock) AsUnion

AsUnion returns a BetaRawContentBlockStartEventContentBlockUnion interface which you can cast to the specific types for more type safety.

Possible runtime types of the union are BetaTextBlock, BetaToolUseBlock.

func (*BetaRawContentBlockStartEventContentBlock) UnmarshalJSON

func (r *BetaRawContentBlockStartEventContentBlock) UnmarshalJSON(data []byte) (err error)

type BetaRawContentBlockStartEventContentBlockType

type BetaRawContentBlockStartEventContentBlockType string
const (
	BetaRawContentBlockStartEventContentBlockTypeText    BetaRawContentBlockStartEventContentBlockType = "text"
	BetaRawContentBlockStartEventContentBlockTypeToolUse BetaRawContentBlockStartEventContentBlockType = "tool_use"
)

func (BetaRawContentBlockStartEventContentBlockType) IsKnown

type BetaRawContentBlockStartEventContentBlockUnion

type BetaRawContentBlockStartEventContentBlockUnion interface {
	// contains filtered or unexported methods
}

Union satisfied by BetaTextBlock or BetaToolUseBlock.

type BetaRawContentBlockStartEventType

type BetaRawContentBlockStartEventType string
const (
	BetaRawContentBlockStartEventTypeContentBlockStart BetaRawContentBlockStartEventType = "content_block_start"
)

func (BetaRawContentBlockStartEventType) IsKnown

type BetaRawContentBlockStopEvent

type BetaRawContentBlockStopEvent struct {
	Index int64                            `json:"index,required"`
	Type  BetaRawContentBlockStopEventType `json:"type,required"`
	JSON  betaRawContentBlockStopEventJSON `json:"-"`
}

func (*BetaRawContentBlockStopEvent) UnmarshalJSON

func (r *BetaRawContentBlockStopEvent) UnmarshalJSON(data []byte) (err error)

type BetaRawContentBlockStopEventType

type BetaRawContentBlockStopEventType string
const (
	BetaRawContentBlockStopEventTypeContentBlockStop BetaRawContentBlockStopEventType = "content_block_stop"
)

func (BetaRawContentBlockStopEventType) IsKnown

type BetaRawMessageDeltaEvent

type BetaRawMessageDeltaEvent struct {
	Delta BetaRawMessageDeltaEventDelta `json:"delta,required"`
	Type  BetaRawMessageDeltaEventType  `json:"type,required"`
	// Billing and rate-limit usage.
	//
	// Anthropic's API bills and rate-limits by token counts, as tokens represent the
	// underlying cost to our systems.
	//
	// Under the hood, the API transforms requests into a format suitable for the
	// model. The model's output then goes through a parsing stage before becoming an
	// API response. As a result, the token counts in `usage` will not match one-to-one
	// with the exact visible content of an API request or response.
	//
	// For example, `output_tokens` will be non-zero, even for an empty string response
	// from Claude.
	Usage BetaMessageDeltaUsage        `json:"usage,required"`
	JSON  betaRawMessageDeltaEventJSON `json:"-"`
}

func (*BetaRawMessageDeltaEvent) UnmarshalJSON

func (r *BetaRawMessageDeltaEvent) UnmarshalJSON(data []byte) (err error)

type BetaRawMessageDeltaEventDelta

type BetaRawMessageDeltaEventDelta struct {
	StopReason   BetaRawMessageDeltaEventDeltaStopReason `json:"stop_reason,required,nullable"`
	StopSequence string                                  `json:"stop_sequence,required,nullable"`
	JSON         betaRawMessageDeltaEventDeltaJSON       `json:"-"`
}

func (*BetaRawMessageDeltaEventDelta) UnmarshalJSON

func (r *BetaRawMessageDeltaEventDelta) UnmarshalJSON(data []byte) (err error)

type BetaRawMessageDeltaEventDeltaStopReason

type BetaRawMessageDeltaEventDeltaStopReason string
const (
	BetaRawMessageDeltaEventDeltaStopReasonEndTurn      BetaRawMessageDeltaEventDeltaStopReason = "end_turn"
	BetaRawMessageDeltaEventDeltaStopReasonMaxTokens    BetaRawMessageDeltaEventDeltaStopReason = "max_tokens"
	BetaRawMessageDeltaEventDeltaStopReasonStopSequence BetaRawMessageDeltaEventDeltaStopReason = "stop_sequence"
	BetaRawMessageDeltaEventDeltaStopReasonToolUse      BetaRawMessageDeltaEventDeltaStopReason = "tool_use"
)

func (BetaRawMessageDeltaEventDeltaStopReason) IsKnown

type BetaRawMessageDeltaEventType

type BetaRawMessageDeltaEventType string
const (
	BetaRawMessageDeltaEventTypeMessageDelta BetaRawMessageDeltaEventType = "message_delta"
)

func (BetaRawMessageDeltaEventType) IsKnown

func (r BetaRawMessageDeltaEventType) IsKnown() bool

type BetaRawMessageStartEvent

type BetaRawMessageStartEvent struct {
	Message BetaMessage                  `json:"message,required"`
	Type    BetaRawMessageStartEventType `json:"type,required"`
	JSON    betaRawMessageStartEventJSON `json:"-"`
}

func (*BetaRawMessageStartEvent) UnmarshalJSON

func (r *BetaRawMessageStartEvent) UnmarshalJSON(data []byte) (err error)

type BetaRawMessageStartEventType

type BetaRawMessageStartEventType string
const (
	BetaRawMessageStartEventTypeMessageStart BetaRawMessageStartEventType = "message_start"
)

func (BetaRawMessageStartEventType) IsKnown

func (r BetaRawMessageStartEventType) IsKnown() bool

type BetaRawMessageStopEvent

type BetaRawMessageStopEvent struct {
	Type BetaRawMessageStopEventType `json:"type,required"`
	JSON betaRawMessageStopEventJSON `json:"-"`
}

func (*BetaRawMessageStopEvent) UnmarshalJSON

func (r *BetaRawMessageStopEvent) UnmarshalJSON(data []byte) (err error)

type BetaRawMessageStopEventType

type BetaRawMessageStopEventType string
const (
	BetaRawMessageStopEventTypeMessageStop BetaRawMessageStopEventType = "message_stop"
)

func (BetaRawMessageStopEventType) IsKnown

func (r BetaRawMessageStopEventType) IsKnown() bool

type BetaRawMessageStreamEvent

type BetaRawMessageStreamEvent struct {
	Type    BetaRawMessageStreamEventType `json:"type,required"`
	Message BetaMessage                   `json:"message"`
	// This field can have the runtime type of [BetaRawMessageDeltaEventDelta],
	// [BetaRawContentBlockDeltaEventDelta].
	Delta interface{} `json:"delta,required"`
	// Billing and rate-limit usage.
	//
	// Anthropic's API bills and rate-limits by token counts, as tokens represent the
	// underlying cost to our systems.
	//
	// Under the hood, the API transforms requests into a format suitable for the
	// model. The model's output then goes through a parsing stage before becoming an
	// API response. As a result, the token counts in `usage` will not match one-to-one
	// with the exact visible content of an API request or response.
	//
	// For example, `output_tokens` will be non-zero, even for an empty string response
	// from Claude.
	Usage BetaMessageDeltaUsage `json:"usage"`
	Index int64                 `json:"index"`
	// This field can have the runtime type of
	// [BetaRawContentBlockStartEventContentBlock].
	ContentBlock interface{}                   `json:"content_block,required"`
	JSON         betaRawMessageStreamEventJSON `json:"-"`
	// contains filtered or unexported fields
}

func (BetaRawMessageStreamEvent) AsUnion

AsUnion returns a BetaRawMessageStreamEventUnion interface which you can cast to the specific types for more type safety.

Possible runtime types of the union are BetaRawMessageStartEvent, BetaRawMessageDeltaEvent, BetaRawMessageStopEvent, BetaRawContentBlockStartEvent, BetaRawContentBlockDeltaEvent, BetaRawContentBlockStopEvent.

func (*BetaRawMessageStreamEvent) UnmarshalJSON

func (r *BetaRawMessageStreamEvent) UnmarshalJSON(data []byte) (err error)

type BetaRawMessageStreamEventType

type BetaRawMessageStreamEventType string
const (
	BetaRawMessageStreamEventTypeMessageStart      BetaRawMessageStreamEventType = "message_start"
	BetaRawMessageStreamEventTypeMessageDelta      BetaRawMessageStreamEventType = "message_delta"
	BetaRawMessageStreamEventTypeMessageStop       BetaRawMessageStreamEventType = "message_stop"
	BetaRawMessageStreamEventTypeContentBlockStart BetaRawMessageStreamEventType = "content_block_start"
	BetaRawMessageStreamEventTypeContentBlockDelta BetaRawMessageStreamEventType = "content_block_delta"
	BetaRawMessageStreamEventTypeContentBlockStop  BetaRawMessageStreamEventType = "content_block_stop"
)

func (BetaRawMessageStreamEventType) IsKnown

func (r BetaRawMessageStreamEventType) IsKnown() bool

type BetaRawMessageStreamEventUnion

type BetaRawMessageStreamEventUnion interface {
	// contains filtered or unexported methods
}

Union satisfied by BetaRawMessageStartEvent, BetaRawMessageDeltaEvent, BetaRawMessageStopEvent, BetaRawContentBlockStartEvent, BetaRawContentBlockDeltaEvent or BetaRawContentBlockStopEvent.

type BetaService

type BetaService struct {
	Options       []option.RequestOption
	Messages      *BetaMessageService
	PromptCaching *BetaPromptCachingService
}

BetaService contains methods and other services that help with interacting with the anthropic API.

Note, unlike clients, this service does not read variables from the environment automatically. You should not instantiate this service directly, and instead use the NewBetaService method instead.

func NewBetaService

func NewBetaService(opts ...option.RequestOption) (r *BetaService)

NewBetaService generates a new service that applies the given options to each request. These options are applied after the parent client's options (if there is one), and before any request-specific options.

type BetaTextBlock

type BetaTextBlock struct {
	Text string            `json:"text,required"`
	Type BetaTextBlockType `json:"type,required"`
	JSON betaTextBlockJSON `json:"-"`
}

func (*BetaTextBlock) UnmarshalJSON

func (r *BetaTextBlock) UnmarshalJSON(data []byte) (err error)

type BetaTextBlockParam

type BetaTextBlockParam struct {
	Text         param.Field[string]                         `json:"text,required"`
	Type         param.Field[BetaTextBlockParamType]         `json:"type,required"`
	CacheControl param.Field[BetaCacheControlEphemeralParam] `json:"cache_control"`
}

func (BetaTextBlockParam) MarshalJSON

func (r BetaTextBlockParam) MarshalJSON() (data []byte, err error)

type BetaTextBlockParamType

type BetaTextBlockParamType string
const (
	BetaTextBlockParamTypeText BetaTextBlockParamType = "text"
)

func (BetaTextBlockParamType) IsKnown

func (r BetaTextBlockParamType) IsKnown() bool

type BetaTextBlockType

type BetaTextBlockType string
const (
	BetaTextBlockTypeText BetaTextBlockType = "text"
)

func (BetaTextBlockType) IsKnown

func (r BetaTextBlockType) IsKnown() bool

type BetaTextDelta

type BetaTextDelta struct {
	Text string            `json:"text,required"`
	Type BetaTextDeltaType `json:"type,required"`
	JSON betaTextDeltaJSON `json:"-"`
}

func (*BetaTextDelta) UnmarshalJSON

func (r *BetaTextDelta) UnmarshalJSON(data []byte) (err error)

type BetaTextDeltaType

type BetaTextDeltaType string
const (
	BetaTextDeltaTypeTextDelta BetaTextDeltaType = "text_delta"
)

func (BetaTextDeltaType) IsKnown

func (r BetaTextDeltaType) IsKnown() bool

type BetaToolBash20241022Name

type BetaToolBash20241022Name string
const (
	BetaToolBash20241022NameBash BetaToolBash20241022Name = "bash"
)

func (BetaToolBash20241022Name) IsKnown

func (r BetaToolBash20241022Name) IsKnown() bool

type BetaToolBash20241022Param

type BetaToolBash20241022Param struct {
	Name         param.Field[BetaToolBash20241022Name]       `json:"name,required"`
	Type         param.Field[BetaToolBash20241022Type]       `json:"type,required"`
	CacheControl param.Field[BetaCacheControlEphemeralParam] `json:"cache_control"`
}

func (BetaToolBash20241022Param) MarshalJSON

func (r BetaToolBash20241022Param) MarshalJSON() (data []byte, err error)

type BetaToolBash20241022Type

type BetaToolBash20241022Type string
const (
	BetaToolBash20241022TypeBash20241022 BetaToolBash20241022Type = "bash_20241022"
)

func (BetaToolBash20241022Type) IsKnown

func (r BetaToolBash20241022Type) IsKnown() bool

type BetaToolChoiceAnyParam

type BetaToolChoiceAnyParam struct {
	Type param.Field[BetaToolChoiceAnyType] `json:"type,required"`
	// Whether to disable parallel tool use.
	//
	// Defaults to `false`. If set to `true`, the model will output exactly one tool
	// use.
	DisableParallelToolUse param.Field[bool] `json:"disable_parallel_tool_use"`
}

The model will use any available tools.

func (BetaToolChoiceAnyParam) MarshalJSON

func (r BetaToolChoiceAnyParam) MarshalJSON() (data []byte, err error)

type BetaToolChoiceAnyType

type BetaToolChoiceAnyType string
const (
	BetaToolChoiceAnyTypeAny BetaToolChoiceAnyType = "any"
)

func (BetaToolChoiceAnyType) IsKnown

func (r BetaToolChoiceAnyType) IsKnown() bool

type BetaToolChoiceAutoParam

type BetaToolChoiceAutoParam struct {
	Type param.Field[BetaToolChoiceAutoType] `json:"type,required"`
	// Whether to disable parallel tool use.
	//
	// Defaults to `false`. If set to `true`, the model will output at most one tool
	// use.
	DisableParallelToolUse param.Field[bool] `json:"disable_parallel_tool_use"`
}

The model will automatically decide whether to use tools.

func (BetaToolChoiceAutoParam) MarshalJSON

func (r BetaToolChoiceAutoParam) MarshalJSON() (data []byte, err error)

type BetaToolChoiceAutoType

type BetaToolChoiceAutoType string
const (
	BetaToolChoiceAutoTypeAuto BetaToolChoiceAutoType = "auto"
)

func (BetaToolChoiceAutoType) IsKnown

func (r BetaToolChoiceAutoType) IsKnown() bool

type BetaToolChoiceParam

type BetaToolChoiceParam struct {
	Type param.Field[BetaToolChoiceType] `json:"type,required"`
	// Whether to disable parallel tool use.
	//
	// Defaults to `false`. If set to `true`, the model will output at most one tool
	// use.
	DisableParallelToolUse param.Field[bool] `json:"disable_parallel_tool_use"`
	// The name of the tool to use.
	Name param.Field[string] `json:"name"`
}

How the model should use the provided tools. The model can use a specific tool, any available tool, or decide by itself.

func (BetaToolChoiceParam) MarshalJSON

func (r BetaToolChoiceParam) MarshalJSON() (data []byte, err error)

type BetaToolChoiceToolParam

type BetaToolChoiceToolParam struct {
	// The name of the tool to use.
	Name param.Field[string]                 `json:"name,required"`
	Type param.Field[BetaToolChoiceToolType] `json:"type,required"`
	// Whether to disable parallel tool use.
	//
	// Defaults to `false`. If set to `true`, the model will output exactly one tool
	// use.
	DisableParallelToolUse param.Field[bool] `json:"disable_parallel_tool_use"`
}

The model will use the specified tool with `tool_choice.name`.

func (BetaToolChoiceToolParam) MarshalJSON

func (r BetaToolChoiceToolParam) MarshalJSON() (data []byte, err error)

type BetaToolChoiceToolType

type BetaToolChoiceToolType string
const (
	BetaToolChoiceToolTypeTool BetaToolChoiceToolType = "tool"
)

func (BetaToolChoiceToolType) IsKnown

func (r BetaToolChoiceToolType) IsKnown() bool

type BetaToolChoiceType

type BetaToolChoiceType string
const (
	BetaToolChoiceTypeAuto BetaToolChoiceType = "auto"
	BetaToolChoiceTypeAny  BetaToolChoiceType = "any"
	BetaToolChoiceTypeTool BetaToolChoiceType = "tool"
)

func (BetaToolChoiceType) IsKnown

func (r BetaToolChoiceType) IsKnown() bool

type BetaToolChoiceUnionParam

type BetaToolChoiceUnionParam interface {
	// contains filtered or unexported methods
}

How the model should use the provided tools. The model can use a specific tool, any available tool, or decide by itself.

Satisfied by BetaToolChoiceAutoParam, BetaToolChoiceAnyParam, BetaToolChoiceToolParam, BetaToolChoiceParam.

type BetaToolComputerUse20241022Name

type BetaToolComputerUse20241022Name string
const (
	BetaToolComputerUse20241022NameComputer BetaToolComputerUse20241022Name = "computer"
)

func (BetaToolComputerUse20241022Name) IsKnown

type BetaToolComputerUse20241022Param

type BetaToolComputerUse20241022Param struct {
	DisplayHeightPx param.Field[int64]                           `json:"display_height_px,required"`
	DisplayWidthPx  param.Field[int64]                           `json:"display_width_px,required"`
	Name            param.Field[BetaToolComputerUse20241022Name] `json:"name,required"`
	Type            param.Field[BetaToolComputerUse20241022Type] `json:"type,required"`
	CacheControl    param.Field[BetaCacheControlEphemeralParam]  `json:"cache_control"`
	DisplayNumber   param.Field[int64]                           `json:"display_number"`
}

func (BetaToolComputerUse20241022Param) MarshalJSON

func (r BetaToolComputerUse20241022Param) MarshalJSON() (data []byte, err error)

type BetaToolComputerUse20241022Type

type BetaToolComputerUse20241022Type string
const (
	BetaToolComputerUse20241022TypeComputer20241022 BetaToolComputerUse20241022Type = "computer_20241022"
)

func (BetaToolComputerUse20241022Type) IsKnown

type BetaToolInputSchemaParam

type BetaToolInputSchemaParam struct {
	Type        param.Field[BetaToolInputSchemaType] `json:"type,required"`
	Properties  param.Field[interface{}]             `json:"properties"`
	ExtraFields map[string]interface{}               `json:"-,extras"`
}

[JSON schema](https://json-schema.org/) for this tool's input.

This defines the shape of the `input` that your tool accepts and that the model will produce.

func (BetaToolInputSchemaParam) MarshalJSON

func (r BetaToolInputSchemaParam) MarshalJSON() (data []byte, err error)

type BetaToolInputSchemaType

type BetaToolInputSchemaType string
const (
	BetaToolInputSchemaTypeObject BetaToolInputSchemaType = "object"
)

func (BetaToolInputSchemaType) IsKnown

func (r BetaToolInputSchemaType) IsKnown() bool

type BetaToolParam

type BetaToolParam struct {
	// [JSON schema](https://json-schema.org/) for this tool's input.
	//
	// This defines the shape of the `input` that your tool accepts and that the model
	// will produce.
	InputSchema  param.Field[BetaToolInputSchemaParam]       `json:"input_schema,required"`
	Name         param.Field[string]                         `json:"name,required"`
	CacheControl param.Field[BetaCacheControlEphemeralParam] `json:"cache_control"`
	// Description of what this tool does.
	//
	// Tool descriptions should be as detailed as possible. The more information that
	// the model has about what the tool is and how to use it, the better it will
	// perform. You can use natural language descriptions to reinforce important
	// aspects of the tool input JSON schema.
	Description param.Field[string]       `json:"description"`
	Type        param.Field[BetaToolType] `json:"type"`
}

func (BetaToolParam) MarshalJSON

func (r BetaToolParam) MarshalJSON() (data []byte, err error)

type BetaToolResultBlockParam

type BetaToolResultBlockParam struct {
	ToolUseID    param.Field[string]                                 `json:"tool_use_id,required"`
	Type         param.Field[BetaToolResultBlockParamType]           `json:"type,required"`
	CacheControl param.Field[BetaCacheControlEphemeralParam]         `json:"cache_control"`
	Content      param.Field[[]BetaToolResultBlockParamContentUnion] `json:"content"`
	IsError      param.Field[bool]                                   `json:"is_error"`
}

func (BetaToolResultBlockParam) MarshalJSON

func (r BetaToolResultBlockParam) MarshalJSON() (data []byte, err error)

type BetaToolResultBlockParamContent

type BetaToolResultBlockParamContent struct {
	CacheControl param.Field[BetaCacheControlEphemeralParam]      `json:"cache_control"`
	Type         param.Field[BetaToolResultBlockParamContentType] `json:"type,required"`
	Text         param.Field[string]                              `json:"text"`
	Source       param.Field[interface{}]                         `json:"source,required"`
}

func (BetaToolResultBlockParamContent) MarshalJSON

func (r BetaToolResultBlockParamContent) MarshalJSON() (data []byte, err error)

type BetaToolResultBlockParamContentType

type BetaToolResultBlockParamContentType string
const (
	BetaToolResultBlockParamContentTypeText  BetaToolResultBlockParamContentType = "text"
	BetaToolResultBlockParamContentTypeImage BetaToolResultBlockParamContentType = "image"
)

func (BetaToolResultBlockParamContentType) IsKnown

type BetaToolResultBlockParamContentUnion

type BetaToolResultBlockParamContentUnion interface {
	// contains filtered or unexported methods
}

Satisfied by BetaTextBlockParam, BetaImageBlockParam, BetaToolResultBlockParamContent.

type BetaToolResultBlockParamType

type BetaToolResultBlockParamType string
const (
	BetaToolResultBlockParamTypeToolResult BetaToolResultBlockParamType = "tool_result"
)

func (BetaToolResultBlockParamType) IsKnown

func (r BetaToolResultBlockParamType) IsKnown() bool

type BetaToolTextEditor20241022Name

type BetaToolTextEditor20241022Name string
const (
	BetaToolTextEditor20241022NameStrReplaceEditor BetaToolTextEditor20241022Name = "str_replace_editor"
)

func (BetaToolTextEditor20241022Name) IsKnown

type BetaToolTextEditor20241022Param

type BetaToolTextEditor20241022Param struct {
	Name         param.Field[BetaToolTextEditor20241022Name] `json:"name,required"`
	Type         param.Field[BetaToolTextEditor20241022Type] `json:"type,required"`
	CacheControl param.Field[BetaCacheControlEphemeralParam] `json:"cache_control"`
}

func (BetaToolTextEditor20241022Param) MarshalJSON

func (r BetaToolTextEditor20241022Param) MarshalJSON() (data []byte, err error)

type BetaToolTextEditor20241022Type

type BetaToolTextEditor20241022Type string
const (
	BetaToolTextEditor20241022TypeTextEditor20241022 BetaToolTextEditor20241022Type = "text_editor_20241022"
)

func (BetaToolTextEditor20241022Type) IsKnown

type BetaToolType

type BetaToolType string
const (
	BetaToolTypeCustom BetaToolType = "custom"
)

func (BetaToolType) IsKnown

func (r BetaToolType) IsKnown() bool

type BetaToolUnionParam

type BetaToolUnionParam struct {
	Type param.Field[BetaToolUnionType] `json:"type"`
	// Description of what this tool does.
	//
	// Tool descriptions should be as detailed as possible. The more information that
	// the model has about what the tool is and how to use it, the better it will
	// perform. You can use natural language descriptions to reinforce important
	// aspects of the tool input JSON schema.
	Description     param.Field[string]                         `json:"description"`
	Name            param.Field[string]                         `json:"name,required"`
	InputSchema     param.Field[interface{}]                    `json:"input_schema,required"`
	CacheControl    param.Field[BetaCacheControlEphemeralParam] `json:"cache_control"`
	DisplayHeightPx param.Field[int64]                          `json:"display_height_px"`
	DisplayWidthPx  param.Field[int64]                          `json:"display_width_px"`
	DisplayNumber   param.Field[int64]                          `json:"display_number"`
}

func (BetaToolUnionParam) MarshalJSON

func (r BetaToolUnionParam) MarshalJSON() (data []byte, err error)

type BetaToolUnionType

type BetaToolUnionType string
const (
	BetaToolUnionTypeCustom             BetaToolUnionType = "custom"
	BetaToolUnionTypeComputer20241022   BetaToolUnionType = "computer_20241022"
	BetaToolUnionTypeBash20241022       BetaToolUnionType = "bash_20241022"
	BetaToolUnionTypeTextEditor20241022 BetaToolUnionType = "text_editor_20241022"
)

func (BetaToolUnionType) IsKnown

func (r BetaToolUnionType) IsKnown() bool

type BetaToolUnionUnionParam

type BetaToolUnionUnionParam interface {
	// contains filtered or unexported methods
}

Satisfied by BetaToolParam, BetaToolComputerUse20241022Param, BetaToolBash20241022Param, BetaToolTextEditor20241022Param, BetaToolUnionParam.

type BetaToolUseBlock

type BetaToolUseBlock struct {
	ID    string               `json:"id,required"`
	Input interface{}          `json:"input,required"`
	Name  string               `json:"name,required"`
	Type  BetaToolUseBlockType `json:"type,required"`
	JSON  betaToolUseBlockJSON `json:"-"`
}

func (*BetaToolUseBlock) UnmarshalJSON

func (r *BetaToolUseBlock) UnmarshalJSON(data []byte) (err error)

type BetaToolUseBlockParam

type BetaToolUseBlockParam struct {
	ID           param.Field[string]                         `json:"id,required"`
	Input        param.Field[interface{}]                    `json:"input,required"`
	Name         param.Field[string]                         `json:"name,required"`
	Type         param.Field[BetaToolUseBlockParamType]      `json:"type,required"`
	CacheControl param.Field[BetaCacheControlEphemeralParam] `json:"cache_control"`
}

func (BetaToolUseBlockParam) MarshalJSON

func (r BetaToolUseBlockParam) MarshalJSON() (data []byte, err error)

type BetaToolUseBlockParamType

type BetaToolUseBlockParamType string
const (
	BetaToolUseBlockParamTypeToolUse BetaToolUseBlockParamType = "tool_use"
)

func (BetaToolUseBlockParamType) IsKnown

func (r BetaToolUseBlockParamType) IsKnown() bool

type BetaToolUseBlockType

type BetaToolUseBlockType string
const (
	BetaToolUseBlockTypeToolUse BetaToolUseBlockType = "tool_use"
)

func (BetaToolUseBlockType) IsKnown

func (r BetaToolUseBlockType) IsKnown() bool

type BetaUsage

type BetaUsage struct {
	// The number of input tokens used to create the cache entry.
	CacheCreationInputTokens int64 `json:"cache_creation_input_tokens,required,nullable"`
	// The number of input tokens read from the cache.
	CacheReadInputTokens int64 `json:"cache_read_input_tokens,required,nullable"`
	// The number of input tokens which were used.
	InputTokens int64 `json:"input_tokens,required"`
	// The number of output tokens which were used.
	OutputTokens int64         `json:"output_tokens,required"`
	JSON         betaUsageJSON `json:"-"`
}

func (*BetaUsage) UnmarshalJSON

func (r *BetaUsage) UnmarshalJSON(data []byte) (err error)

type Client

type Client struct {
	Options     []option.RequestOption
	Completions *CompletionService
	Messages    *MessageService
	Beta        *BetaService
}

Client creates a struct with services and top level methods that help with interacting with the anthropic API. You should not instantiate this client directly, and instead use the NewClient method instead.

func NewClient

func NewClient(opts ...option.RequestOption) (r *Client)

NewClient generates a new client with the default option read from the environment (ANTHROPIC_API_KEY, ANTHROPIC_AUTH_TOKEN). The option passed in as arguments are applied after these default arguments, and all option will be passed down to the services and requests that this client makes.

func (*Client) Delete

func (r *Client) Delete(ctx context.Context, path string, params interface{}, res interface{}, opts ...option.RequestOption) error

Delete makes a DELETE request with the given URL, params, and optionally deserializes to a response. See [Execute] documentation on the params and response.

func (*Client) Execute

func (r *Client) Execute(ctx context.Context, method string, path string, params interface{}, res interface{}, opts ...option.RequestOption) error

Execute makes a request with the given context, method, URL, request params, response, and request options. This is useful for hitting undocumented endpoints while retaining the base URL, auth, retries, and other options from the client.

If a byte slice or an io.Reader is supplied to params, it will be used as-is for the request body.

The params is by default serialized into the body using encoding/json. If your type implements a MarshalJSON function, it will be used instead to serialize the request. If a URLQuery method is implemented, the returned url.Values will be used as query strings to the url.

If your params struct uses param.Field, you must provide either [MarshalJSON], [URLQuery], and/or [MarshalForm] functions. It is undefined behavior to use a struct uses param.Field without specifying how it is serialized.

Any "…Params" object defined in this library can be used as the request argument. Note that 'path' arguments will not be forwarded into the url.

The response body will be deserialized into the res variable, depending on its type:

  • A pointer to a *http.Response is populated by the raw response.
  • A pointer to a byte array will be populated with the contents of the request body.
  • A pointer to any other type uses this library's default JSON decoding, which respects UnmarshalJSON if it is defined on the type.
  • A nil value will not read the response body.

For even greater flexibility, see option.WithResponseInto and option.WithResponseBodyInto.

func (*Client) Get

func (r *Client) Get(ctx context.Context, path string, params interface{}, res interface{}, opts ...option.RequestOption) error

Get makes a GET request with the given URL, params, and optionally deserializes to a response. See [Execute] documentation on the params and response.

func (*Client) Patch

func (r *Client) Patch(ctx context.Context, path string, params interface{}, res interface{}, opts ...option.RequestOption) error

Patch makes a PATCH request with the given URL, params, and optionally deserializes to a response. See [Execute] documentation on the params and response.

func (*Client) Post

func (r *Client) Post(ctx context.Context, path string, params interface{}, res interface{}, opts ...option.RequestOption) error

Post makes a POST request with the given URL, params, and optionally deserializes to a response. See [Execute] documentation on the params and response.

func (*Client) Put

func (r *Client) Put(ctx context.Context, path string, params interface{}, res interface{}, opts ...option.RequestOption) error

Put makes a PUT request with the given URL, params, and optionally deserializes to a response. See [Execute] documentation on the params and response.

type Completion

type Completion struct {
	// Unique object identifier.
	//
	// The format and length of IDs may change over time.
	ID string `json:"id,required"`
	// The resulting completion up to and excluding the stop sequences.
	Completion string `json:"completion,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"`
	// The reason that we stopped.
	//
	// This may be one the following values:
	//
	//   - `"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,nullable"`
	// Object type.
	//
	// For Text Completions, this is always `"completion"`.
	Type CompletionType `json:"type,required"`
	JSON completionJSON `json:"-"`
}

func (*Completion) UnmarshalJSON

func (r *Completion) UnmarshalJSON(data []byte) (err error)

type CompletionNewParams

type CompletionNewParams struct {
	// The maximum number of tokens to generate before stopping.
	//
	// Note that our models may stop _before_ reaching this maximum. This parameter
	// only specifies the absolute maximum number of tokens to generate.
	MaxTokensToSample param.Field[int64] `json:"max_tokens_to_sample,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 param.Field[Model] `json:"model,required"`
	// The prompt that you want Claude to complete.
	//
	// For proper response generation you will need to format your prompt using
	// alternating `\n\nHuman:` and `\n\nAssistant:` conversational turns. For example:
	//
	// “`
	// "\n\nHuman: {userQuestion}\n\nAssistant:"
	// “`
	//
	// See [prompt validation](https://docs.anthropic.com/en/api/prompt-validation) and
	// our guide to
	// [prompt design](https://docs.anthropic.com/en/docs/intro-to-prompting) for more
	// details.
	Prompt param.Field[string] `json:"prompt,required"`
	// An object describing metadata about the request.
	Metadata param.Field[MetadataParam] `json:"metadata"`
	// Sequences that will cause the model to stop generating.
	//
	// Our models stop on `"\n\nHuman:"`, and may include additional built-in stop
	// sequences in the future. By providing the stop_sequences parameter, you may
	// include additional strings that will cause the model to stop generating.
	StopSequences param.Field[[]string] `json:"stop_sequences"`
	// Amount of randomness injected into the response.
	//
	// Defaults to `1.0`. Ranges from `0.0` to `1.0`. Use `temperature` closer to `0.0`
	// for analytical / multiple choice, and closer to `1.0` for creative and
	// generative tasks.
	//
	// Note that even with `temperature` of `0.0`, the results will not be fully
	// deterministic.
	Temperature param.Field[float64] `json:"temperature"`
	// Only sample from the top K options for each subsequent token.
	//
	// Used to remove "long tail" low probability responses.
	// [Learn more technical details here](https://towardsdatascience.com/how-to-sample-from-language-models-682bceb97277).
	//
	// Recommended for advanced use cases only. You usually only need to use
	// `temperature`.
	TopK param.Field[int64] `json:"top_k"`
	// Use nucleus sampling.
	//
	// In nucleus sampling, we compute the cumulative distribution over all the options
	// for each subsequent token in decreasing probability order and cut it off once it
	// reaches a particular probability specified by `top_p`. You should either alter
	// `temperature` or `top_p`, but not both.
	//
	// Recommended for advanced use cases only. You usually only need to use
	// `temperature`.
	TopP param.Field[float64] `json:"top_p"`
}

func (CompletionNewParams) MarshalJSON

func (r CompletionNewParams) MarshalJSON() (data []byte, err error)

type CompletionService

type CompletionService struct {
	Options []option.RequestOption
}

CompletionService contains methods and other services that help with interacting with the anthropic API.

Note, unlike clients, this service does not read variables from the environment automatically. You should not instantiate this service directly, and instead use the NewCompletionService method instead.

func NewCompletionService

func NewCompletionService(opts ...option.RequestOption) (r *CompletionService)

NewCompletionService generates a new service that applies the given options to each request. These options are applied after the parent client's options (if there is one), and before any request-specific options.

func (*CompletionService) New

[Legacy] Create a Text Completion.

The Text Completions API is a legacy API. We recommend using the [Messages API](https://docs.anthropic.com/en/api/messages) going forward.

Future models and features will not be compatible with Text Completions. See our [migration guide](https://docs.anthropic.com/en/api/migrating-from-text-completions-to-messages) for guidance in migrating from Text Completions to Messages.

Note: If you choose to set a timeout for this request, we recommend 10 minutes.

func (*CompletionService) NewStreaming

func (r *CompletionService) NewStreaming(ctx context.Context, body CompletionNewParams, opts ...option.RequestOption) (stream *ssestream.Stream[Completion])

[Legacy] Create a Text Completion.

The Text Completions API is a legacy API. We recommend using the [Messages API](https://docs.anthropic.com/en/api/messages) going forward.

Future models and features will not be compatible with Text Completions. See our [migration guide](https://docs.anthropic.com/en/api/migrating-from-text-completions-to-messages) for guidance in migrating from Text Completions to Messages.

Note: If you choose to set a timeout for this request, we recommend 10 minutes.

type CompletionType

type CompletionType string

Object type.

For Text Completions, this is always `"completion"`.

const (
	CompletionTypeCompletion CompletionType = "completion"
)

func (CompletionType) IsKnown

func (r CompletionType) IsKnown() bool

type ContentBlock

type ContentBlock struct {
	Type  ContentBlockType `json:"type,required"`
	Text  string           `json:"text"`
	ID    string           `json:"id"`
	Name  string           `json:"name"`
	Input json.RawMessage  `json:"input,required"`
	JSON  contentBlockJSON `json:"-"`
	// contains filtered or unexported fields
}

func (ContentBlock) AsUnion

func (r ContentBlock) AsUnion() ContentBlockUnion

AsUnion returns a ContentBlockUnion interface which you can cast to the specific types for more type safety.

Possible runtime types of the union are TextBlock, ToolUseBlock.

func (*ContentBlock) UnmarshalJSON

func (r *ContentBlock) UnmarshalJSON(data []byte) (err error)

type ContentBlockDeltaEvent

type ContentBlockDeltaEvent struct {
	Delta ContentBlockDeltaEventDelta `json:"delta,required"`
	Index int64                       `json:"index,required"`
	Type  ContentBlockDeltaEventType  `json:"type,required"`
	JSON  contentBlockDeltaEventJSON  `json:"-"`
}

func (*ContentBlockDeltaEvent) UnmarshalJSON

func (r *ContentBlockDeltaEvent) UnmarshalJSON(data []byte) (err error)

type ContentBlockDeltaEventDelta

type ContentBlockDeltaEventDelta struct {
	Type        ContentBlockDeltaEventDeltaType `json:"type,required"`
	Text        string                          `json:"text"`
	PartialJSON string                          `json:"partial_json"`
	JSON        contentBlockDeltaEventDeltaJSON `json:"-"`
	// contains filtered or unexported fields
}

func (ContentBlockDeltaEventDelta) AsUnion

AsUnion returns a ContentBlockDeltaEventDeltaUnion interface which you can cast to the specific types for more type safety.

Possible runtime types of the union are TextDelta, InputJSONDelta.

func (*ContentBlockDeltaEventDelta) UnmarshalJSON

func (r *ContentBlockDeltaEventDelta) UnmarshalJSON(data []byte) (err error)

type ContentBlockDeltaEventDeltaType

type ContentBlockDeltaEventDeltaType string
const (
	ContentBlockDeltaEventDeltaTypeTextDelta      ContentBlockDeltaEventDeltaType = "text_delta"
	ContentBlockDeltaEventDeltaTypeInputJSONDelta ContentBlockDeltaEventDeltaType = "input_json_delta"
)

func (ContentBlockDeltaEventDeltaType) IsKnown

type ContentBlockDeltaEventDeltaUnion

type ContentBlockDeltaEventDeltaUnion interface {
	// contains filtered or unexported methods
}

Union satisfied by TextDelta or InputJSONDelta.

type ContentBlockDeltaEventType

type ContentBlockDeltaEventType string
const (
	ContentBlockDeltaEventTypeContentBlockDelta ContentBlockDeltaEventType = "content_block_delta"
)

func (ContentBlockDeltaEventType) IsKnown

func (r ContentBlockDeltaEventType) IsKnown() bool

type ContentBlockStartEvent

type ContentBlockStartEvent struct {
	ContentBlock ContentBlockStartEventContentBlock `json:"content_block,required"`
	Index        int64                              `json:"index,required"`
	Type         ContentBlockStartEventType         `json:"type,required"`
	JSON         contentBlockStartEventJSON         `json:"-"`
}

func (*ContentBlockStartEvent) UnmarshalJSON

func (r *ContentBlockStartEvent) UnmarshalJSON(data []byte) (err error)

type ContentBlockStartEventContentBlock

type ContentBlockStartEventContentBlock struct {
	Type  ContentBlockStartEventContentBlockType `json:"type,required"`
	Text  string                                 `json:"text"`
	ID    string                                 `json:"id"`
	Name  string                                 `json:"name"`
	Input json.RawMessage                        `json:"input,required"`
	JSON  contentBlockStartEventContentBlockJSON `json:"-"`
	// contains filtered or unexported fields
}

func (ContentBlockStartEventContentBlock) AsUnion

AsUnion returns a ContentBlockStartEventContentBlockUnion interface which you can cast to the specific types for more type safety.

Possible runtime types of the union are TextBlock, ToolUseBlock.

func (*ContentBlockStartEventContentBlock) UnmarshalJSON

func (r *ContentBlockStartEventContentBlock) UnmarshalJSON(data []byte) (err error)

type ContentBlockStartEventContentBlockType

type ContentBlockStartEventContentBlockType string
const (
	ContentBlockStartEventContentBlockTypeText    ContentBlockStartEventContentBlockType = "text"
	ContentBlockStartEventContentBlockTypeToolUse ContentBlockStartEventContentBlockType = "tool_use"
)

func (ContentBlockStartEventContentBlockType) IsKnown

type ContentBlockStartEventContentBlockUnion

type ContentBlockStartEventContentBlockUnion interface {
	// contains filtered or unexported methods
}

Union satisfied by TextBlock or ToolUseBlock.

type ContentBlockStartEventType

type ContentBlockStartEventType string
const (
	ContentBlockStartEventTypeContentBlockStart ContentBlockStartEventType = "content_block_start"
)

func (ContentBlockStartEventType) IsKnown

func (r ContentBlockStartEventType) IsKnown() bool

type ContentBlockStopEvent

type ContentBlockStopEvent struct {
	Index int64                     `json:"index,required"`
	Type  ContentBlockStopEventType `json:"type,required"`
	JSON  contentBlockStopEventJSON `json:"-"`
}

func (*ContentBlockStopEvent) UnmarshalJSON

func (r *ContentBlockStopEvent) UnmarshalJSON(data []byte) (err error)

type ContentBlockStopEventType

type ContentBlockStopEventType string
const (
	ContentBlockStopEventTypeContentBlockStop ContentBlockStopEventType = "content_block_stop"
)

func (ContentBlockStopEventType) IsKnown

func (r ContentBlockStopEventType) IsKnown() bool

type ContentBlockType

type ContentBlockType string
const (
	ContentBlockTypeText    ContentBlockType = "text"
	ContentBlockTypeToolUse ContentBlockType = "tool_use"
)

func (ContentBlockType) IsKnown

func (r ContentBlockType) IsKnown() bool

type ContentBlockUnion

type ContentBlockUnion interface {
	// contains filtered or unexported methods
}

Union satisfied by TextBlock or ToolUseBlock.

type Error

type Error = apierror.Error

type ImageBlockParam

type ImageBlockParam struct {
	Source param.Field[ImageBlockParamSource] `json:"source,required"`
	Type   param.Field[ImageBlockParamType]   `json:"type,required"`
}

func NewImageBlockBase64

func NewImageBlockBase64(mediaType string, encodedData string) ImageBlockParam

func (ImageBlockParam) MarshalJSON

func (r ImageBlockParam) MarshalJSON() (data []byte, err error)

type ImageBlockParamSource

type ImageBlockParamSource struct {
	Data      param.Field[string]                         `json:"data,required" format:"byte"`
	MediaType param.Field[ImageBlockParamSourceMediaType] `json:"media_type,required"`
	Type      param.Field[ImageBlockParamSourceType]      `json:"type,required"`
}

func (ImageBlockParamSource) MarshalJSON

func (r ImageBlockParamSource) MarshalJSON() (data []byte, err error)

type ImageBlockParamSourceMediaType

type ImageBlockParamSourceMediaType string
const (
	ImageBlockParamSourceMediaTypeImageJPEG ImageBlockParamSourceMediaType = "image/jpeg"
	ImageBlockParamSourceMediaTypeImagePNG  ImageBlockParamSourceMediaType = "image/png"
	ImageBlockParamSourceMediaTypeImageGIF  ImageBlockParamSourceMediaType = "image/gif"
	ImageBlockParamSourceMediaTypeImageWebP ImageBlockParamSourceMediaType = "image/webp"
)

func (ImageBlockParamSourceMediaType) IsKnown

type ImageBlockParamSourceType

type ImageBlockParamSourceType string
const (
	ImageBlockParamSourceTypeBase64 ImageBlockParamSourceType = "base64"
)

func (ImageBlockParamSourceType) IsKnown

func (r ImageBlockParamSourceType) IsKnown() bool

type ImageBlockParamType

type ImageBlockParamType string
const (
	ImageBlockParamTypeImage ImageBlockParamType = "image"
)

func (ImageBlockParamType) IsKnown

func (r ImageBlockParamType) IsKnown() bool

type InputJSONDelta

type InputJSONDelta struct {
	PartialJSON string             `json:"partial_json,required"`
	Type        InputJSONDeltaType `json:"type,required"`
	JSON        inputJSONDeltaJSON `json:"-"`
}

func (*InputJSONDelta) UnmarshalJSON

func (r *InputJSONDelta) UnmarshalJSON(data []byte) (err error)

type InputJSONDeltaType

type InputJSONDeltaType string
const (
	InputJSONDeltaTypeInputJSONDelta InputJSONDeltaType = "input_json_delta"
)

func (InputJSONDeltaType) IsKnown

func (r InputJSONDeltaType) IsKnown() bool

type Message

type Message struct {
	// Unique object identifier.
	//
	// The format and length of IDs may change over time.
	ID string `json:"id,required"`
	// Content generated by the model.
	//
	// This is an array of content blocks, each of which has a `type` that determines
	// its shape.
	//
	// Example:
	//
	// “`json
	// [{ "type": "text", "text": "Hi, I'm Claude." }]
	// “`
	//
	// If the request input `messages` ended with an `assistant` turn, then the
	// response `content` will continue directly from that last turn. You can use this
	// to constrain the model's output.
	//
	// For example, if the input `messages` were:
	//
	// “`json
	// [
	//
	//	{
	//	  "role": "user",
	//	  "content": "What's the Greek name for Sun? (A) Sol (B) Helios (C) Sun"
	//	},
	//	{ "role": "assistant", "content": "The best answer is (" }
	//
	// ]
	// “`
	//
	// Then the response `content` might be:
	//
	// “`json
	// [{ "type": "text", "text": "B)" }]
	// “`
	Content []ContentBlock `json:"content,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"`
	// Conversational role of the generated message.
	//
	// This will always be `"assistant"`.
	Role MessageRole `json:"role,required"`
	// 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.
	StopReason MessageStopReason `json:"stop_reason,required,nullable"`
	// 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,nullable"`
	// Object type.
	//
	// For Messages, this is always `"message"`.
	Type MessageType `json:"type,required"`
	// Billing and rate-limit usage.
	//
	// Anthropic's API bills and rate-limits by token counts, as tokens represent the
	// underlying cost to our systems.
	//
	// Under the hood, the API transforms requests into a format suitable for the
	// model. The model's output then goes through a parsing stage before becoming an
	// API response. As a result, the token counts in `usage` will not match one-to-one
	// with the exact visible content of an API request or response.
	//
	// For example, `output_tokens` will be non-zero, even for an empty string response
	// from Claude.
	Usage Usage       `json:"usage,required"`
	JSON  messageJSON `json:"-"`
}

ToParam converts a Message to a MessageParam, which can be used when constructing a new Create

func (*Message) Accumulate

func (a *Message) Accumulate(event MessageStreamEvent) error

Accumulate builds up the Message incrementally from a MessageStreamEvent. The Message then can be used as any other Message, except with the caveat that the Message.JSON field which normally can be used to inspect the JSON sent over the network may not be populated fully.

message := anthropic.Message{}
for stream.Next() {
	event := stream.Current()
	message.Accumulate(event)
}

func (*Message) ToParam

func (r *Message) ToParam() MessageParam

ToParam converts a Message to a MessageParam which can be used when making another network request. This is useful when interacting with Claude conversationally or when tool calling.

messages := []anthropic.MessageParam{
	anthropic.NewUserMessage(anthropic.NewTextBlock("What is my first name?")),
}

message, err := client.Messages.New(context.TODO(), anthropic.MessageNewParams{
	MaxTokens: anthropic.F(int64(1024)),
	Messages: anthropic.F(messages),
	Model: anthropic.F(anthropic.ModelClaude_3_5_Sonnet_20240620),
})

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{
	MaxTokens: anthropic.F(int64(1024)),
	Messages: anthropic.F(messages),
	Model: anthropic.F(anthropic.ModelClaude_3_5_Sonnet_20240620),
})

func (*Message) UnmarshalJSON

func (r *Message) UnmarshalJSON(data []byte) (err error)

type MessageDeltaEvent

type MessageDeltaEvent struct {
	Delta MessageDeltaEventDelta `json:"delta,required"`
	Type  MessageDeltaEventType  `json:"type,required"`
	// Billing and rate-limit usage.
	//
	// Anthropic's API bills and rate-limits by token counts, as tokens represent the
	// underlying cost to our systems.
	//
	// Under the hood, the API transforms requests into a format suitable for the
	// model. The model's output then goes through a parsing stage before becoming an
	// API response. As a result, the token counts in `usage` will not match one-to-one
	// with the exact visible content of an API request or response.
	//
	// For example, `output_tokens` will be non-zero, even for an empty string response
	// from Claude.
	Usage MessageDeltaUsage     `json:"usage,required"`
	JSON  messageDeltaEventJSON `json:"-"`
}

func (*MessageDeltaEvent) UnmarshalJSON

func (r *MessageDeltaEvent) UnmarshalJSON(data []byte) (err error)

type MessageDeltaEventDelta

type MessageDeltaEventDelta struct {
	StopReason   MessageDeltaEventDeltaStopReason `json:"stop_reason,required,nullable"`
	StopSequence string                           `json:"stop_sequence,required,nullable"`
	JSON         messageDeltaEventDeltaJSON       `json:"-"`
}

func (*MessageDeltaEventDelta) UnmarshalJSON

func (r *MessageDeltaEventDelta) UnmarshalJSON(data []byte) (err error)

type MessageDeltaEventDeltaStopReason

type MessageDeltaEventDeltaStopReason string
const (
	MessageDeltaEventDeltaStopReasonEndTurn      MessageDeltaEventDeltaStopReason = "end_turn"
	MessageDeltaEventDeltaStopReasonMaxTokens    MessageDeltaEventDeltaStopReason = "max_tokens"
	MessageDeltaEventDeltaStopReasonStopSequence MessageDeltaEventDeltaStopReason = "stop_sequence"
	MessageDeltaEventDeltaStopReasonToolUse      MessageDeltaEventDeltaStopReason = "tool_use"
)

func (MessageDeltaEventDeltaStopReason) IsKnown

type MessageDeltaEventType

type MessageDeltaEventType string
const (
	MessageDeltaEventTypeMessageDelta MessageDeltaEventType = "message_delta"
)

func (MessageDeltaEventType) IsKnown

func (r MessageDeltaEventType) IsKnown() bool

type MessageDeltaUsage

type MessageDeltaUsage struct {
	// The cumulative number of output tokens which were used.
	OutputTokens int64                 `json:"output_tokens,required"`
	JSON         messageDeltaUsageJSON `json:"-"`
}

func (*MessageDeltaUsage) UnmarshalJSON

func (r *MessageDeltaUsage) UnmarshalJSON(data []byte) (err error)

type MessageNewParams

type MessageNewParams struct {
	// The maximum number of tokens to generate before stopping.
	//
	// Note that our models may stop _before_ reaching this maximum. This parameter
	// only specifies the absolute maximum number of tokens to generate.
	//
	// Different models have different maximum values for this parameter. See
	// [models](https://docs.anthropic.com/en/docs/models-overview) for details.
	MaxTokens param.Field[int64] `json:"max_tokens,required"`
	// Input messages.
	//
	// Our models are trained to operate on alternating `user` and `assistant`
	// conversational turns. When creating a new `Message`, you specify the prior
	// conversational turns with the `messages` parameter, and the model then generates
	// the next `Message` in the conversation. Consecutive `user` or `assistant` turns
	// in your request will be combined into a single turn.
	//
	// Each input message must be an object with a `role` and `content`. You can
	// specify a single `user`-role message, or you can include multiple `user` and
	// `assistant` messages.
	//
	// If the final message uses the `assistant` role, the response content will
	// continue immediately from the content in that message. This can be used to
	// constrain part of the model's response.
	//
	// Example with a single `user` message:
	//
	// “`json
	// [{ "role": "user", "content": "Hello, Claude" }]
	// “`
	//
	// Example with multiple conversational turns:
	//
	// “`json
	// [
	//
	//	{ "role": "user", "content": "Hello there." },
	//	{ "role": "assistant", "content": "Hi, I'm Claude. How can I help you?" },
	//	{ "role": "user", "content": "Can you explain LLMs in plain English?" }
	//
	// ]
	// “`
	//
	// Example with a partially-filled response from Claude:
	//
	// “`json
	// [
	//
	//	{
	//	  "role": "user",
	//	  "content": "What's the Greek name for Sun? (A) Sol (B) Helios (C) Sun"
	//	},
	//	{ "role": "assistant", "content": "The best answer is (" }
	//
	// ]
	// “`
	//
	// Each input message `content` may be either a single `string` or an array of
	// content blocks, where each block has a specific `type`. Using a `string` for
	// `content` is shorthand for an array of one content block of type `"text"`. The
	// following input messages are equivalent:
	//
	// “`json
	// { "role": "user", "content": "Hello, Claude" }
	// “`
	//
	// “`json
	// { "role": "user", "content": [{ "type": "text", "text": "Hello, Claude" }] }
	// “`
	//
	// Starting with Claude 3 models, you can also send image content blocks:
	//
	// “`json
	//
	//	{
	//	  "role": "user",
	//	  "content": [
	//	    {
	//	      "type": "image",
	//	      "source": {
	//	        "type": "base64",
	//	        "media_type": "image/jpeg",
	//	        "data": "/9j/4AAQSkZJRg..."
	//	      }
	//	    },
	//	    { "type": "text", "text": "What is in this image?" }
	//	  ]
	//	}
	//
	// “`
	//
	// We currently support the `base64` source type for images, and the `image/jpeg`,
	// `image/png`, `image/gif`, and `image/webp` media types.
	//
	// See [examples](https://docs.anthropic.com/en/api/messages-examples#vision) for
	// more input examples.
	//
	// Note that if you want to include a
	// [system prompt](https://docs.anthropic.com/en/docs/system-prompts), you can use
	// the top-level `system` parameter — there is no `"system"` role for input
	// messages in the Messages API.
	Messages param.Field[[]MessageParam] `json:"messages,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 param.Field[Model] `json:"model,required"`
	// An object describing metadata about the request.
	Metadata param.Field[MetadataParam] `json:"metadata"`
	// Custom text sequences that will cause the model to stop generating.
	//
	// Our models will normally stop when they have naturally completed their turn,
	// which will result in a response `stop_reason` of `"end_turn"`.
	//
	// If you want the model to stop generating when it encounters custom strings of
	// text, you can use the `stop_sequences` parameter. If the model encounters one of
	// the custom sequences, the response `stop_reason` value will be `"stop_sequence"`
	// and the response `stop_sequence` value will contain the matched stop sequence.
	StopSequences param.Field[[]string] `json:"stop_sequences"`
	// System prompt.
	//
	// A system prompt is a way of providing context and instructions to Claude, such
	// as specifying a particular goal or role. See our
	// [guide to system prompts](https://docs.anthropic.com/en/docs/system-prompts).
	System param.Field[[]TextBlockParam] `json:"system"`
	// Amount of randomness injected into the response.
	//
	// Defaults to `1.0`. Ranges from `0.0` to `1.0`. Use `temperature` closer to `0.0`
	// for analytical / multiple choice, and closer to `1.0` for creative and
	// generative tasks.
	//
	// Note that even with `temperature` of `0.0`, the results will not be fully
	// deterministic.
	Temperature param.Field[float64] `json:"temperature"`
	// How the model should use the provided tools. The model can use a specific tool,
	// any available tool, or decide by itself.
	ToolChoice param.Field[ToolChoiceUnionParam] `json:"tool_choice"`
	// Definitions of tools that the model may use.
	//
	// If you include `tools` in your API request, the model may return `tool_use`
	// content blocks that represent the model's use of those tools. You can then run
	// those tools using the tool input generated by the model and then optionally
	// return results back to the model using `tool_result` content blocks.
	//
	// Each tool definition includes:
	//
	//   - `name`: Name of the tool.
	//   - `description`: Optional, but strongly-recommended description of the tool.
	//   - `input_schema`: [JSON schema](https://json-schema.org/) for the tool `input`
	//     shape that the model will produce in `tool_use` output content blocks.
	//
	// For example, if you defined `tools` as:
	//
	// “`json
	// [
	//
	//	{
	//	  "name": "get_stock_price",
	//	  "description": "Get the current stock price for a given ticker symbol.",
	//	  "input_schema": {
	//	    "type": "object",
	//	    "properties": {
	//	      "ticker": {
	//	        "type": "string",
	//	        "description": "The stock ticker symbol, e.g. AAPL for Apple Inc."
	//	      }
	//	    },
	//	    "required": ["ticker"]
	//	  }
	//	}
	//
	// ]
	// “`
	//
	// And then asked the model "What's the S&P 500 at today?", the model might produce
	// `tool_use` content blocks in the response like this:
	//
	// “`json
	// [
	//
	//	{
	//	  "type": "tool_use",
	//	  "id": "toolu_01D7FLrfh4GYq7yT1ULFeyMV",
	//	  "name": "get_stock_price",
	//	  "input": { "ticker": "^GSPC" }
	//	}
	//
	// ]
	// “`
	//
	// You might then run your `get_stock_price` tool with `{"ticker": "^GSPC"}` as an
	// input, and return the following back to the model in a subsequent `user`
	// message:
	//
	// “`json
	// [
	//
	//	{
	//	  "type": "tool_result",
	//	  "tool_use_id": "toolu_01D7FLrfh4GYq7yT1ULFeyMV",
	//	  "content": "259.75 USD"
	//	}
	//
	// ]
	// “`
	//
	// Tools can be used for workflows that include running client-side tools and
	// functions, or more generally whenever you want the model to produce a particular
	// JSON structure of output.
	//
	// See our [guide](https://docs.anthropic.com/en/docs/tool-use) for more details.
	Tools param.Field[[]ToolParam] `json:"tools"`
	// Only sample from the top K options for each subsequent token.
	//
	// Used to remove "long tail" low probability responses.
	// [Learn more technical details here](https://towardsdatascience.com/how-to-sample-from-language-models-682bceb97277).
	//
	// Recommended for advanced use cases only. You usually only need to use
	// `temperature`.
	TopK param.Field[int64] `json:"top_k"`
	// Use nucleus sampling.
	//
	// In nucleus sampling, we compute the cumulative distribution over all the options
	// for each subsequent token in decreasing probability order and cut it off once it
	// reaches a particular probability specified by `top_p`. You should either alter
	// `temperature` or `top_p`, but not both.
	//
	// Recommended for advanced use cases only. You usually only need to use
	// `temperature`.
	TopP param.Field[float64] `json:"top_p"`
}

func (MessageNewParams) MarshalJSON

func (r MessageNewParams) MarshalJSON() (data []byte, err error)

type MessageParam

type MessageParam struct {
	Content param.Field[[]MessageParamContentUnion] `json:"content,required"`
	Role    param.Field[MessageParamRole]           `json:"role,required"`
}

func NewAssistantMessage

func NewAssistantMessage(blocks ...MessageParamContentUnion) MessageParam

func NewUserMessage

func NewUserMessage(blocks ...MessageParamContentUnion) MessageParam

func (MessageParam) MarshalJSON

func (r MessageParam) MarshalJSON() (data []byte, err error)

type MessageParamContent

type MessageParamContent struct {
	Type      param.Field[MessageParamContentType] `json:"type,required"`
	Text      param.Field[string]                  `json:"text"`
	Source    param.Field[interface{}]             `json:"source,required"`
	ID        param.Field[string]                  `json:"id"`
	Name      param.Field[string]                  `json:"name"`
	Input     param.Field[interface{}]             `json:"input,required"`
	ToolUseID param.Field[string]                  `json:"tool_use_id"`
	IsError   param.Field[bool]                    `json:"is_error"`
	Content   param.Field[interface{}]             `json:"content,required"`
}

func (MessageParamContent) MarshalJSON

func (r MessageParamContent) MarshalJSON() (data []byte, err error)

type MessageParamContentType

type MessageParamContentType string
const (
	MessageParamContentTypeText       MessageParamContentType = "text"
	MessageParamContentTypeImage      MessageParamContentType = "image"
	MessageParamContentTypeToolUse    MessageParamContentType = "tool_use"
	MessageParamContentTypeToolResult MessageParamContentType = "tool_result"
)

func (MessageParamContentType) IsKnown

func (r MessageParamContentType) IsKnown() bool

type MessageParamContentUnion

type MessageParamContentUnion interface {
	// contains filtered or unexported methods
}

Satisfied by TextBlockParam, ImageBlockParam, ToolUseBlockParam, ToolResultBlockParam, MessageParamContent.

type MessageParamRole

type MessageParamRole string
const (
	MessageParamRoleUser      MessageParamRole = "user"
	MessageParamRoleAssistant MessageParamRole = "assistant"
)

func (MessageParamRole) IsKnown

func (r MessageParamRole) IsKnown() bool

type MessageRole

type MessageRole string

Conversational role of the generated message.

This will always be `"assistant"`.

const (
	MessageRoleAssistant MessageRole = "assistant"
)

func (MessageRole) IsKnown

func (r MessageRole) IsKnown() bool

type MessageService

type MessageService struct {
	Options []option.RequestOption
}

MessageService contains methods and other services that help with interacting with the anthropic API.

Note, unlike clients, this service does not read variables from the environment automatically. You should not instantiate this service directly, and instead use the NewMessageService method instead.

func NewMessageService

func NewMessageService(opts ...option.RequestOption) (r *MessageService)

NewMessageService generates a new service that applies the given options to each request. These options are applied after the parent client's options (if there is one), and before any request-specific options.

func (*MessageService) New

func (r *MessageService) New(ctx context.Context, body MessageNewParams, opts ...option.RequestOption) (res *Message, err error)

Send a structured list of input messages with text and/or image content, and the model will generate the next message in the conversation.

The Messages API can be used for either single queries or stateless multi-turn conversations.

Note: If you choose to set a timeout for this request, we recommend 10 minutes.

func (*MessageService) NewStreaming

func (r *MessageService) NewStreaming(ctx context.Context, body MessageNewParams, opts ...option.RequestOption) (stream *ssestream.Stream[MessageStreamEvent])

Send a structured list of input messages with text and/or image content, and the model will generate the next message in the conversation.

The Messages API can be used for either single queries or stateless multi-turn conversations.

Note: If you choose to set a timeout for this request, we recommend 10 minutes.

type MessageStartEvent

type MessageStartEvent struct {
	Message Message               `json:"message,required"`
	Type    MessageStartEventType `json:"type,required"`
	JSON    messageStartEventJSON `json:"-"`
}

func (*MessageStartEvent) UnmarshalJSON

func (r *MessageStartEvent) UnmarshalJSON(data []byte) (err error)

type MessageStartEventType

type MessageStartEventType string
const (
	MessageStartEventTypeMessageStart MessageStartEventType = "message_start"
)

func (MessageStartEventType) IsKnown

func (r MessageStartEventType) IsKnown() bool

type MessageStopEvent

type MessageStopEvent struct {
	Type MessageStopEventType `json:"type,required"`
	JSON messageStopEventJSON `json:"-"`
}

func (*MessageStopEvent) UnmarshalJSON

func (r *MessageStopEvent) UnmarshalJSON(data []byte) (err error)

type MessageStopEventType

type MessageStopEventType string
const (
	MessageStopEventTypeMessageStop MessageStopEventType = "message_stop"
)

func (MessageStopEventType) IsKnown

func (r MessageStopEventType) IsKnown() bool

type MessageStopReason

type MessageStopReason string

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.

const (
	MessageStopReasonEndTurn      MessageStopReason = "end_turn"
	MessageStopReasonMaxTokens    MessageStopReason = "max_tokens"
	MessageStopReasonStopSequence MessageStopReason = "stop_sequence"
	MessageStopReasonToolUse      MessageStopReason = "tool_use"
)

func (MessageStopReason) IsKnown

func (r MessageStopReason) IsKnown() bool

type MessageStreamEvent

type MessageStreamEvent struct {
	Type    MessageStreamEventType `json:"type,required"`
	Message Message                `json:"message"`
	// This field can have the runtime type of [MessageDeltaEventDelta],
	// [ContentBlockDeltaEventDelta].
	Delta interface{} `json:"delta,required"`
	// Billing and rate-limit usage.
	//
	// Anthropic's API bills and rate-limits by token counts, as tokens represent the
	// underlying cost to our systems.
	//
	// Under the hood, the API transforms requests into a format suitable for the
	// model. The model's output then goes through a parsing stage before becoming an
	// API response. As a result, the token counts in `usage` will not match one-to-one
	// with the exact visible content of an API request or response.
	//
	// For example, `output_tokens` will be non-zero, even for an empty string response
	// from Claude.
	Usage MessageDeltaUsage `json:"usage"`
	Index int64             `json:"index"`
	// This field can have the runtime type of [ContentBlockStartEventContentBlock].
	ContentBlock interface{}            `json:"content_block,required"`
	JSON         messageStreamEventJSON `json:"-"`
	// contains filtered or unexported fields
}

func (MessageStreamEvent) AsUnion

AsUnion returns a MessageStreamEventUnion interface which you can cast to the specific types for more type safety.

Possible runtime types of the union are MessageStartEvent, MessageDeltaEvent, MessageStopEvent, ContentBlockStartEvent, ContentBlockDeltaEvent, ContentBlockStopEvent.

func (*MessageStreamEvent) UnmarshalJSON

func (r *MessageStreamEvent) UnmarshalJSON(data []byte) (err error)

type MessageStreamEventType

type MessageStreamEventType string
const (
	MessageStreamEventTypeMessageStart      MessageStreamEventType = "message_start"
	MessageStreamEventTypeMessageDelta      MessageStreamEventType = "message_delta"
	MessageStreamEventTypeMessageStop       MessageStreamEventType = "message_stop"
	MessageStreamEventTypeContentBlockStart MessageStreamEventType = "content_block_start"
	MessageStreamEventTypeContentBlockDelta MessageStreamEventType = "content_block_delta"
	MessageStreamEventTypeContentBlockStop  MessageStreamEventType = "content_block_stop"
)

func (MessageStreamEventType) IsKnown

func (r MessageStreamEventType) IsKnown() bool

type MessageStreamEventUnion

type MessageStreamEventUnion interface {
	// contains filtered or unexported methods
}

Union satisfied by MessageStartEvent, MessageDeltaEvent, MessageStopEvent, ContentBlockStartEvent, ContentBlockDeltaEvent or ContentBlockStopEvent.

type MessageType

type MessageType string

Object type.

For Messages, this is always `"message"`.

const (
	MessageTypeMessage MessageType = "message"
)

func (MessageType) IsKnown

func (r MessageType) IsKnown() bool

type MetadataParam

type MetadataParam struct {
	// An external identifier for the user who is associated with the request.
	//
	// This should be a uuid, hash value, or other opaque identifier. Anthropic may use
	// this id to help detect abuse. Do not include any identifying information such as
	// name, email address, or phone number.
	UserID param.Field[string] `json:"user_id"`
}

func (MetadataParam) MarshalJSON

func (r MetadataParam) MarshalJSON() (data []byte, err error)

type Model

type Model = string
const (
	// Our most intelligent model
	ModelClaude3_5SonnetLatest Model = "claude-3-5-sonnet-latest"
	// Our most intelligent model
	ModelClaude3_5Sonnet20241022 Model = "claude-3-5-sonnet-20241022"
	// Our previous most intelligent model
	ModelClaude_3_5_Sonnet_20240620 Model = "claude-3-5-sonnet-20240620"
	// Excels at writing and complex tasks
	ModelClaude3OpusLatest Model = "claude-3-opus-latest"
	// Excels at writing and complex tasks
	ModelClaude_3_Opus_20240229 Model = "claude-3-opus-20240229"
	// Balance of speed and intelligence
	ModelClaude_3_Sonnet_20240229 Model = "claude-3-sonnet-20240229"
	// Fast and cost-effective
	ModelClaude_3_Haiku_20240307 Model = "claude-3-haiku-20240307"
	ModelClaude_2_1              Model = "claude-2.1"
	ModelClaude_2_0              Model = "claude-2.0"
	ModelClaude_Instant_1_2      Model = "claude-instant-1.2"
)

type PromptCachingBetaCacheControlEphemeralParam

type PromptCachingBetaCacheControlEphemeralParam struct {
	Type param.Field[PromptCachingBetaCacheControlEphemeralType] `json:"type,required"`
}

func (PromptCachingBetaCacheControlEphemeralParam) MarshalJSON

func (r PromptCachingBetaCacheControlEphemeralParam) MarshalJSON() (data []byte, err error)

type PromptCachingBetaCacheControlEphemeralType

type PromptCachingBetaCacheControlEphemeralType string
const (
	PromptCachingBetaCacheControlEphemeralTypeEphemeral PromptCachingBetaCacheControlEphemeralType = "ephemeral"
)

func (PromptCachingBetaCacheControlEphemeralType) IsKnown

type PromptCachingBetaImageBlockParam

type PromptCachingBetaImageBlockParam struct {
	Source       param.Field[PromptCachingBetaImageBlockParamSource]      `json:"source,required"`
	Type         param.Field[PromptCachingBetaImageBlockParamType]        `json:"type,required"`
	CacheControl param.Field[PromptCachingBetaCacheControlEphemeralParam] `json:"cache_control"`
}

func (PromptCachingBetaImageBlockParam) MarshalJSON

func (r PromptCachingBetaImageBlockParam) MarshalJSON() (data []byte, err error)

type PromptCachingBetaImageBlockParamSource

type PromptCachingBetaImageBlockParamSource struct {
	Data      param.Field[string]                                          `json:"data,required" format:"byte"`
	MediaType param.Field[PromptCachingBetaImageBlockParamSourceMediaType] `json:"media_type,required"`
	Type      param.Field[PromptCachingBetaImageBlockParamSourceType]      `json:"type,required"`
}

func (PromptCachingBetaImageBlockParamSource) MarshalJSON

func (r PromptCachingBetaImageBlockParamSource) MarshalJSON() (data []byte, err error)

type PromptCachingBetaImageBlockParamSourceMediaType

type PromptCachingBetaImageBlockParamSourceMediaType string
const (
	PromptCachingBetaImageBlockParamSourceMediaTypeImageJPEG PromptCachingBetaImageBlockParamSourceMediaType = "image/jpeg"
	PromptCachingBetaImageBlockParamSourceMediaTypeImagePNG  PromptCachingBetaImageBlockParamSourceMediaType = "image/png"
	PromptCachingBetaImageBlockParamSourceMediaTypeImageGIF  PromptCachingBetaImageBlockParamSourceMediaType = "image/gif"
	PromptCachingBetaImageBlockParamSourceMediaTypeImageWebP PromptCachingBetaImageBlockParamSourceMediaType = "image/webp"
)

func (PromptCachingBetaImageBlockParamSourceMediaType) IsKnown

type PromptCachingBetaImageBlockParamSourceType

type PromptCachingBetaImageBlockParamSourceType string
const (
	PromptCachingBetaImageBlockParamSourceTypeBase64 PromptCachingBetaImageBlockParamSourceType = "base64"
)

func (PromptCachingBetaImageBlockParamSourceType) IsKnown

type PromptCachingBetaImageBlockParamType

type PromptCachingBetaImageBlockParamType string
const (
	PromptCachingBetaImageBlockParamTypeImage PromptCachingBetaImageBlockParamType = "image"
)

func (PromptCachingBetaImageBlockParamType) IsKnown

type PromptCachingBetaMessage

type PromptCachingBetaMessage struct {
	// Unique object identifier.
	//
	// The format and length of IDs may change over time.
	ID string `json:"id,required"`
	// Content generated by the model.
	//
	// This is an array of content blocks, each of which has a `type` that determines
	// its shape.
	//
	// Example:
	//
	// “`json
	// [{ "type": "text", "text": "Hi, I'm Claude." }]
	// “`
	//
	// If the request input `messages` ended with an `assistant` turn, then the
	// response `content` will continue directly from that last turn. You can use this
	// to constrain the model's output.
	//
	// For example, if the input `messages` were:
	//
	// “`json
	// [
	//
	//	{
	//	  "role": "user",
	//	  "content": "What's the Greek name for Sun? (A) Sol (B) Helios (C) Sun"
	//	},
	//	{ "role": "assistant", "content": "The best answer is (" }
	//
	// ]
	// “`
	//
	// Then the response `content` might be:
	//
	// “`json
	// [{ "type": "text", "text": "B)" }]
	// “`
	Content []ContentBlock `json:"content,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"`
	// Conversational role of the generated message.
	//
	// This will always be `"assistant"`.
	Role PromptCachingBetaMessageRole `json:"role,required"`
	// 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.
	StopReason PromptCachingBetaMessageStopReason `json:"stop_reason,required,nullable"`
	// 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,nullable"`
	// Object type.
	//
	// For Messages, this is always `"message"`.
	Type PromptCachingBetaMessageType `json:"type,required"`
	// Billing and rate-limit usage.
	//
	// Anthropic's API bills and rate-limits by token counts, as tokens represent the
	// underlying cost to our systems.
	//
	// Under the hood, the API transforms requests into a format suitable for the
	// model. The model's output then goes through a parsing stage before becoming an
	// API response. As a result, the token counts in `usage` will not match one-to-one
	// with the exact visible content of an API request or response.
	//
	// For example, `output_tokens` will be non-zero, even for an empty string response
	// from Claude.
	Usage PromptCachingBetaUsage       `json:"usage,required"`
	JSON  promptCachingBetaMessageJSON `json:"-"`
}

func (*PromptCachingBetaMessage) UnmarshalJSON

func (r *PromptCachingBetaMessage) UnmarshalJSON(data []byte) (err error)

type PromptCachingBetaMessageParam

type PromptCachingBetaMessageParam struct {
	Content param.Field[[]PromptCachingBetaMessageParamContentUnion] `json:"content,required"`
	Role    param.Field[PromptCachingBetaMessageParamRole]           `json:"role,required"`
}

func (PromptCachingBetaMessageParam) MarshalJSON

func (r PromptCachingBetaMessageParam) MarshalJSON() (data []byte, err error)

type PromptCachingBetaMessageParamContent

type PromptCachingBetaMessageParamContent struct {
	CacheControl param.Field[PromptCachingBetaCacheControlEphemeralParam] `json:"cache_control"`
	Type         param.Field[PromptCachingBetaMessageParamContentType]    `json:"type,required"`
	Text         param.Field[string]                                      `json:"text"`
	Source       param.Field[interface{}]                                 `json:"source,required"`
	ID           param.Field[string]                                      `json:"id"`
	Name         param.Field[string]                                      `json:"name"`
	Input        param.Field[interface{}]                                 `json:"input,required"`
	ToolUseID    param.Field[string]                                      `json:"tool_use_id"`
	IsError      param.Field[bool]                                        `json:"is_error"`
	Content      param.Field[interface{}]                                 `json:"content,required"`
}

func (PromptCachingBetaMessageParamContent) MarshalJSON

func (r PromptCachingBetaMessageParamContent) MarshalJSON() (data []byte, err error)

type PromptCachingBetaMessageParamContentType

type PromptCachingBetaMessageParamContentType string
const (
	PromptCachingBetaMessageParamContentTypeText       PromptCachingBetaMessageParamContentType = "text"
	PromptCachingBetaMessageParamContentTypeImage      PromptCachingBetaMessageParamContentType = "image"
	PromptCachingBetaMessageParamContentTypeToolUse    PromptCachingBetaMessageParamContentType = "tool_use"
	PromptCachingBetaMessageParamContentTypeToolResult PromptCachingBetaMessageParamContentType = "tool_result"
)

func (PromptCachingBetaMessageParamContentType) IsKnown

type PromptCachingBetaMessageParamRole

type PromptCachingBetaMessageParamRole string
const (
	PromptCachingBetaMessageParamRoleUser      PromptCachingBetaMessageParamRole = "user"
	PromptCachingBetaMessageParamRoleAssistant PromptCachingBetaMessageParamRole = "assistant"
)

func (PromptCachingBetaMessageParamRole) IsKnown

type PromptCachingBetaMessageRole

type PromptCachingBetaMessageRole string

Conversational role of the generated message.

This will always be `"assistant"`.

const (
	PromptCachingBetaMessageRoleAssistant PromptCachingBetaMessageRole = "assistant"
)

func (PromptCachingBetaMessageRole) IsKnown

func (r PromptCachingBetaMessageRole) IsKnown() bool

type PromptCachingBetaMessageStopReason

type PromptCachingBetaMessageStopReason string

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.

const (
	PromptCachingBetaMessageStopReasonEndTurn      PromptCachingBetaMessageStopReason = "end_turn"
	PromptCachingBetaMessageStopReasonMaxTokens    PromptCachingBetaMessageStopReason = "max_tokens"
	PromptCachingBetaMessageStopReasonStopSequence PromptCachingBetaMessageStopReason = "stop_sequence"
	PromptCachingBetaMessageStopReasonToolUse      PromptCachingBetaMessageStopReason = "tool_use"
)

func (PromptCachingBetaMessageStopReason) IsKnown

type PromptCachingBetaMessageType

type PromptCachingBetaMessageType string

Object type.

For Messages, this is always `"message"`.

const (
	PromptCachingBetaMessageTypeMessage PromptCachingBetaMessageType = "message"
)

func (PromptCachingBetaMessageType) IsKnown

func (r PromptCachingBetaMessageType) IsKnown() bool

type PromptCachingBetaTextBlockParam

type PromptCachingBetaTextBlockParam struct {
	Text         param.Field[string]                                      `json:"text,required"`
	Type         param.Field[PromptCachingBetaTextBlockParamType]         `json:"type,required"`
	CacheControl param.Field[PromptCachingBetaCacheControlEphemeralParam] `json:"cache_control"`
}

func (PromptCachingBetaTextBlockParam) MarshalJSON

func (r PromptCachingBetaTextBlockParam) MarshalJSON() (data []byte, err error)

type PromptCachingBetaTextBlockParamType

type PromptCachingBetaTextBlockParamType string
const (
	PromptCachingBetaTextBlockParamTypeText PromptCachingBetaTextBlockParamType = "text"
)

func (PromptCachingBetaTextBlockParamType) IsKnown

type PromptCachingBetaToolInputSchemaParam

type PromptCachingBetaToolInputSchemaParam struct {
	Type        param.Field[PromptCachingBetaToolInputSchemaType] `json:"type,required"`
	Properties  param.Field[interface{}]                          `json:"properties"`
	ExtraFields map[string]interface{}                            `json:"-,extras"`
}

[JSON schema](https://json-schema.org/) for this tool's input.

This defines the shape of the `input` that your tool accepts and that the model will produce.

func (PromptCachingBetaToolInputSchemaParam) MarshalJSON

func (r PromptCachingBetaToolInputSchemaParam) MarshalJSON() (data []byte, err error)

type PromptCachingBetaToolInputSchemaType

type PromptCachingBetaToolInputSchemaType string
const (
	PromptCachingBetaToolInputSchemaTypeObject PromptCachingBetaToolInputSchemaType = "object"
)

func (PromptCachingBetaToolInputSchemaType) IsKnown

type PromptCachingBetaToolParam

type PromptCachingBetaToolParam struct {
	// [JSON schema](https://json-schema.org/) for this tool's input.
	//
	// This defines the shape of the `input` that your tool accepts and that the model
	// will produce.
	InputSchema  param.Field[PromptCachingBetaToolInputSchemaParam]       `json:"input_schema,required"`
	Name         param.Field[string]                                      `json:"name,required"`
	CacheControl param.Field[PromptCachingBetaCacheControlEphemeralParam] `json:"cache_control"`
	// Description of what this tool does.
	//
	// Tool descriptions should be as detailed as possible. The more information that
	// the model has about what the tool is and how to use it, the better it will
	// perform. You can use natural language descriptions to reinforce important
	// aspects of the tool input JSON schema.
	Description param.Field[string] `json:"description"`
}

func (PromptCachingBetaToolParam) MarshalJSON

func (r PromptCachingBetaToolParam) MarshalJSON() (data []byte, err error)

type PromptCachingBetaToolResultBlockParam

type PromptCachingBetaToolResultBlockParam struct {
	ToolUseID    param.Field[string]                                            `json:"tool_use_id,required"`
	Type         param.Field[PromptCachingBetaToolResultBlockParamType]         `json:"type,required"`
	CacheControl param.Field[PromptCachingBetaCacheControlEphemeralParam]       `json:"cache_control"`
	Content      param.Field[PromptCachingBetaToolResultBlockParamContentUnion] `json:"content"`
	IsError      param.Field[bool]                                              `json:"is_error"`
}

func (PromptCachingBetaToolResultBlockParam) MarshalJSON

func (r PromptCachingBetaToolResultBlockParam) MarshalJSON() (data []byte, err error)

type PromptCachingBetaToolResultBlockParamContentArray

type PromptCachingBetaToolResultBlockParamContentArray []PromptCachingBetaToolResultBlockParamContentArrayUnionItem

func (PromptCachingBetaToolResultBlockParamContentArray) ImplementsPromptCachingBetaToolResultBlockParamContentUnion

func (r PromptCachingBetaToolResultBlockParamContentArray) ImplementsPromptCachingBetaToolResultBlockParamContentUnion()

type PromptCachingBetaToolResultBlockParamContentArrayItem

type PromptCachingBetaToolResultBlockParamContentArrayItem struct {
	CacheControl param.Field[PromptCachingBetaCacheControlEphemeralParam]           `json:"cache_control"`
	Type         param.Field[PromptCachingBetaToolResultBlockParamContentArrayType] `json:"type,required"`
	Text         param.Field[string]                                                `json:"text"`
	Source       param.Field[interface{}]                                           `json:"source,required"`
}

func (PromptCachingBetaToolResultBlockParamContentArrayItem) MarshalJSON

type PromptCachingBetaToolResultBlockParamContentArrayType

type PromptCachingBetaToolResultBlockParamContentArrayType string
const (
	PromptCachingBetaToolResultBlockParamContentArrayTypeText  PromptCachingBetaToolResultBlockParamContentArrayType = "text"
	PromptCachingBetaToolResultBlockParamContentArrayTypeImage PromptCachingBetaToolResultBlockParamContentArrayType = "image"
)

func (PromptCachingBetaToolResultBlockParamContentArrayType) IsKnown

type PromptCachingBetaToolResultBlockParamContentArrayUnionItem

type PromptCachingBetaToolResultBlockParamContentArrayUnionItem interface {
	// contains filtered or unexported methods
}

Satisfied by PromptCachingBetaTextBlockParam, PromptCachingBetaImageBlockParam, PromptCachingBetaToolResultBlockParamContentArrayItem.

type PromptCachingBetaToolResultBlockParamContentUnion

type PromptCachingBetaToolResultBlockParamContentUnion interface {
	ImplementsPromptCachingBetaToolResultBlockParamContentUnion()
}

Satisfied by [shared.UnionString], PromptCachingBetaToolResultBlockParamContentArray.

type PromptCachingBetaToolResultBlockParamType

type PromptCachingBetaToolResultBlockParamType string
const (
	PromptCachingBetaToolResultBlockParamTypeToolResult PromptCachingBetaToolResultBlockParamType = "tool_result"
)

func (PromptCachingBetaToolResultBlockParamType) IsKnown

type PromptCachingBetaToolUseBlockParam

type PromptCachingBetaToolUseBlockParam struct {
	ID           param.Field[string]                                      `json:"id,required"`
	Input        param.Field[interface{}]                                 `json:"input,required"`
	Name         param.Field[string]                                      `json:"name,required"`
	Type         param.Field[PromptCachingBetaToolUseBlockParamType]      `json:"type,required"`
	CacheControl param.Field[PromptCachingBetaCacheControlEphemeralParam] `json:"cache_control"`
}

func (PromptCachingBetaToolUseBlockParam) MarshalJSON

func (r PromptCachingBetaToolUseBlockParam) MarshalJSON() (data []byte, err error)

type PromptCachingBetaToolUseBlockParamType

type PromptCachingBetaToolUseBlockParamType string
const (
	PromptCachingBetaToolUseBlockParamTypeToolUse PromptCachingBetaToolUseBlockParamType = "tool_use"
)

func (PromptCachingBetaToolUseBlockParamType) IsKnown

type PromptCachingBetaUsage

type PromptCachingBetaUsage struct {
	// The number of input tokens used to create the cache entry.
	CacheCreationInputTokens int64 `json:"cache_creation_input_tokens,required,nullable"`
	// The number of input tokens read from the cache.
	CacheReadInputTokens int64 `json:"cache_read_input_tokens,required,nullable"`
	// The number of input tokens which were used.
	InputTokens int64 `json:"input_tokens,required"`
	// The number of output tokens which were used.
	OutputTokens int64                      `json:"output_tokens,required"`
	JSON         promptCachingBetaUsageJSON `json:"-"`
}

func (*PromptCachingBetaUsage) UnmarshalJSON

func (r *PromptCachingBetaUsage) UnmarshalJSON(data []byte) (err error)

type RawPromptCachingBetaMessageStartEvent

type RawPromptCachingBetaMessageStartEvent struct {
	Message PromptCachingBetaMessage                  `json:"message,required"`
	Type    RawPromptCachingBetaMessageStartEventType `json:"type,required"`
	JSON    rawPromptCachingBetaMessageStartEventJSON `json:"-"`
}

func (*RawPromptCachingBetaMessageStartEvent) UnmarshalJSON

func (r *RawPromptCachingBetaMessageStartEvent) UnmarshalJSON(data []byte) (err error)

type RawPromptCachingBetaMessageStartEventType

type RawPromptCachingBetaMessageStartEventType string
const (
	RawPromptCachingBetaMessageStartEventTypeMessageStart RawPromptCachingBetaMessageStartEventType = "message_start"
)

func (RawPromptCachingBetaMessageStartEventType) IsKnown

type RawPromptCachingBetaMessageStreamEvent

type RawPromptCachingBetaMessageStreamEvent struct {
	Type    RawPromptCachingBetaMessageStreamEventType `json:"type,required"`
	Message PromptCachingBetaMessage                   `json:"message"`
	// This field can have the runtime type of [MessageDeltaEventDelta],
	// [ContentBlockDeltaEventDelta].
	Delta interface{} `json:"delta,required"`
	// Billing and rate-limit usage.
	//
	// Anthropic's API bills and rate-limits by token counts, as tokens represent the
	// underlying cost to our systems.
	//
	// Under the hood, the API transforms requests into a format suitable for the
	// model. The model's output then goes through a parsing stage before becoming an
	// API response. As a result, the token counts in `usage` will not match one-to-one
	// with the exact visible content of an API request or response.
	//
	// For example, `output_tokens` will be non-zero, even for an empty string response
	// from Claude.
	Usage MessageDeltaUsage `json:"usage"`
	Index int64             `json:"index"`
	// This field can have the runtime type of [ContentBlockStartEventContentBlock].
	ContentBlock interface{}                                `json:"content_block,required"`
	JSON         rawPromptCachingBetaMessageStreamEventJSON `json:"-"`
	// contains filtered or unexported fields
}

func (RawPromptCachingBetaMessageStreamEvent) AsUnion

AsUnion returns a RawPromptCachingBetaMessageStreamEventUnion interface which you can cast to the specific types for more type safety.

Possible runtime types of the union are RawPromptCachingBetaMessageStartEvent, MessageDeltaEvent, MessageStopEvent, ContentBlockStartEvent, ContentBlockDeltaEvent, ContentBlockStopEvent.

func (*RawPromptCachingBetaMessageStreamEvent) UnmarshalJSON

func (r *RawPromptCachingBetaMessageStreamEvent) UnmarshalJSON(data []byte) (err error)

type RawPromptCachingBetaMessageStreamEventType

type RawPromptCachingBetaMessageStreamEventType string
const (
	RawPromptCachingBetaMessageStreamEventTypeMessageStart      RawPromptCachingBetaMessageStreamEventType = "message_start"
	RawPromptCachingBetaMessageStreamEventTypeMessageDelta      RawPromptCachingBetaMessageStreamEventType = "message_delta"
	RawPromptCachingBetaMessageStreamEventTypeMessageStop       RawPromptCachingBetaMessageStreamEventType = "message_stop"
	RawPromptCachingBetaMessageStreamEventTypeContentBlockStart RawPromptCachingBetaMessageStreamEventType = "content_block_start"
	RawPromptCachingBetaMessageStreamEventTypeContentBlockDelta RawPromptCachingBetaMessageStreamEventType = "content_block_delta"
	RawPromptCachingBetaMessageStreamEventTypeContentBlockStop  RawPromptCachingBetaMessageStreamEventType = "content_block_stop"
)

func (RawPromptCachingBetaMessageStreamEventType) IsKnown

type RawPromptCachingBetaMessageStreamEventUnion

type RawPromptCachingBetaMessageStreamEventUnion interface {
	// contains filtered or unexported methods
}

Union satisfied by RawPromptCachingBetaMessageStartEvent, MessageDeltaEvent, MessageStopEvent, ContentBlockStartEvent, ContentBlockDeltaEvent or ContentBlockStopEvent.

type TextBlock

type TextBlock struct {
	Text string        `json:"text,required"`
	Type TextBlockType `json:"type,required"`
	JSON textBlockJSON `json:"-"`
}

func (*TextBlock) UnmarshalJSON

func (r *TextBlock) UnmarshalJSON(data []byte) (err error)

type TextBlockParam

type TextBlockParam struct {
	Text param.Field[string]             `json:"text,required"`
	Type param.Field[TextBlockParamType] `json:"type,required"`
}

func NewTextBlock

func NewTextBlock(text string) TextBlockParam

func (TextBlockParam) MarshalJSON

func (r TextBlockParam) MarshalJSON() (data []byte, err error)

type TextBlockParamType

type TextBlockParamType string
const (
	TextBlockParamTypeText TextBlockParamType = "text"
)

func (TextBlockParamType) IsKnown

func (r TextBlockParamType) IsKnown() bool

type TextBlockType

type TextBlockType string
const (
	TextBlockTypeText TextBlockType = "text"
)

func (TextBlockType) IsKnown

func (r TextBlockType) IsKnown() bool

type TextDelta

type TextDelta struct {
	Text string        `json:"text,required"`
	Type TextDeltaType `json:"type,required"`
	JSON textDeltaJSON `json:"-"`
}

func (*TextDelta) UnmarshalJSON

func (r *TextDelta) UnmarshalJSON(data []byte) (err error)

type TextDeltaType

type TextDeltaType string
const (
	TextDeltaTypeTextDelta TextDeltaType = "text_delta"
)

func (TextDeltaType) IsKnown

func (r TextDeltaType) IsKnown() bool

type ToolChoiceAnyParam

type ToolChoiceAnyParam struct {
	Type param.Field[ToolChoiceAnyType] `json:"type,required"`
	// Whether to disable parallel tool use.
	//
	// Defaults to `false`. If set to `true`, the model will output exactly one tool
	// use.
	DisableParallelToolUse param.Field[bool] `json:"disable_parallel_tool_use"`
}

The model will use any available tools.

func (ToolChoiceAnyParam) MarshalJSON

func (r ToolChoiceAnyParam) MarshalJSON() (data []byte, err error)

type ToolChoiceAnyType

type ToolChoiceAnyType string
const (
	ToolChoiceAnyTypeAny ToolChoiceAnyType = "any"
)

func (ToolChoiceAnyType) IsKnown

func (r ToolChoiceAnyType) IsKnown() bool

type ToolChoiceAutoParam

type ToolChoiceAutoParam struct {
	Type param.Field[ToolChoiceAutoType] `json:"type,required"`
	// Whether to disable parallel tool use.
	//
	// Defaults to `false`. If set to `true`, the model will output at most one tool
	// use.
	DisableParallelToolUse param.Field[bool] `json:"disable_parallel_tool_use"`
}

The model will automatically decide whether to use tools.

func (ToolChoiceAutoParam) MarshalJSON

func (r ToolChoiceAutoParam) MarshalJSON() (data []byte, err error)

type ToolChoiceAutoType

type ToolChoiceAutoType string
const (
	ToolChoiceAutoTypeAuto ToolChoiceAutoType = "auto"
)

func (ToolChoiceAutoType) IsKnown

func (r ToolChoiceAutoType) IsKnown() bool

type ToolChoiceParam

type ToolChoiceParam struct {
	Type param.Field[ToolChoiceType] `json:"type,required"`
	// Whether to disable parallel tool use.
	//
	// Defaults to `false`. If set to `true`, the model will output at most one tool
	// use.
	DisableParallelToolUse param.Field[bool] `json:"disable_parallel_tool_use"`
	// The name of the tool to use.
	Name param.Field[string] `json:"name"`
}

How the model should use the provided tools. The model can use a specific tool, any available tool, or decide by itself.

func (ToolChoiceParam) MarshalJSON

func (r ToolChoiceParam) MarshalJSON() (data []byte, err error)

type ToolChoiceToolParam

type ToolChoiceToolParam struct {
	// The name of the tool to use.
	Name param.Field[string]             `json:"name,required"`
	Type param.Field[ToolChoiceToolType] `json:"type,required"`
	// Whether to disable parallel tool use.
	//
	// Defaults to `false`. If set to `true`, the model will output exactly one tool
	// use.
	DisableParallelToolUse param.Field[bool] `json:"disable_parallel_tool_use"`
}

The model will use the specified tool with `tool_choice.name`.

func (ToolChoiceToolParam) MarshalJSON

func (r ToolChoiceToolParam) MarshalJSON() (data []byte, err error)

type ToolChoiceToolType

type ToolChoiceToolType string
const (
	ToolChoiceToolTypeTool ToolChoiceToolType = "tool"
)

func (ToolChoiceToolType) IsKnown

func (r ToolChoiceToolType) IsKnown() bool

type ToolChoiceType

type ToolChoiceType string
const (
	ToolChoiceTypeAuto ToolChoiceType = "auto"
	ToolChoiceTypeAny  ToolChoiceType = "any"
	ToolChoiceTypeTool ToolChoiceType = "tool"
)

func (ToolChoiceType) IsKnown

func (r ToolChoiceType) IsKnown() bool

type ToolChoiceUnionParam

type ToolChoiceUnionParam interface {
	// contains filtered or unexported methods
}

How the model should use the provided tools. The model can use a specific tool, any available tool, or decide by itself.

Satisfied by ToolChoiceAutoParam, ToolChoiceAnyParam, ToolChoiceToolParam, ToolChoiceParam.

type ToolInputSchemaParam

type ToolInputSchemaParam struct {
	Type        param.Field[ToolInputSchemaType] `json:"type,required"`
	Properties  param.Field[interface{}]         `json:"properties"`
	ExtraFields map[string]interface{}           `json:"-,extras"`
}

[JSON schema](https://json-schema.org/) for this tool's input.

This defines the shape of the `input` that your tool accepts and that the model will produce.

func (ToolInputSchemaParam) MarshalJSON

func (r ToolInputSchemaParam) MarshalJSON() (data []byte, err error)

type ToolInputSchemaType

type ToolInputSchemaType string
const (
	ToolInputSchemaTypeObject ToolInputSchemaType = "object"
)

func (ToolInputSchemaType) IsKnown

func (r ToolInputSchemaType) IsKnown() bool

type ToolParam

type ToolParam struct {
	// [JSON schema](https://json-schema.org/) for this tool's input.
	//
	// This defines the shape of the `input` that your tool accepts and that the model
	// will produce.
	InputSchema param.Field[interface{}] `json:"input_schema,required"`
	Name        param.Field[string]      `json:"name,required"`
	// Description of what this tool does.
	//
	// Tool descriptions should be as detailed as possible. The more information that
	// the model has about what the tool is and how to use it, the better it will
	// perform. You can use natural language descriptions to reinforce important
	// aspects of the tool input JSON schema.
	Description param.Field[string] `json:"description"`
}

func (ToolParam) MarshalJSON

func (r ToolParam) MarshalJSON() (data []byte, err error)

type ToolResultBlockParam

type ToolResultBlockParam struct {
	ToolUseID param.Field[string]                             `json:"tool_use_id,required"`
	Type      param.Field[ToolResultBlockParamType]           `json:"type,required"`
	Content   param.Field[[]ToolResultBlockParamContentUnion] `json:"content"`
	IsError   param.Field[bool]                               `json:"is_error"`
}

func NewToolResultBlock

func NewToolResultBlock(toolUseID string, content string, isError bool) ToolResultBlockParam

func (ToolResultBlockParam) MarshalJSON

func (r ToolResultBlockParam) MarshalJSON() (data []byte, err error)

type ToolResultBlockParamContent

type ToolResultBlockParamContent struct {
	Type   param.Field[ToolResultBlockParamContentType] `json:"type,required"`
	Text   param.Field[string]                          `json:"text"`
	Source param.Field[interface{}]                     `json:"source,required"`
}

func (ToolResultBlockParamContent) MarshalJSON

func (r ToolResultBlockParamContent) MarshalJSON() (data []byte, err error)

type ToolResultBlockParamContentType

type ToolResultBlockParamContentType string
const (
	ToolResultBlockParamContentTypeText  ToolResultBlockParamContentType = "text"
	ToolResultBlockParamContentTypeImage ToolResultBlockParamContentType = "image"
)

func (ToolResultBlockParamContentType) IsKnown

type ToolResultBlockParamContentUnion

type ToolResultBlockParamContentUnion interface {
	// contains filtered or unexported methods
}

Satisfied by TextBlockParam, ImageBlockParam, ToolResultBlockParamContent.

type ToolResultBlockParamType

type ToolResultBlockParamType string
const (
	ToolResultBlockParamTypeToolResult ToolResultBlockParamType = "tool_result"
)

func (ToolResultBlockParamType) IsKnown

func (r ToolResultBlockParamType) IsKnown() bool

type ToolUseBlock

type ToolUseBlock struct {
	ID    string           `json:"id,required"`
	Input json.RawMessage  `json:"input,required"`
	Name  string           `json:"name,required"`
	Type  ToolUseBlockType `json:"type,required"`
	JSON  toolUseBlockJSON `json:"-"`
}

func (*ToolUseBlock) UnmarshalJSON

func (r *ToolUseBlock) UnmarshalJSON(data []byte) (err error)

type ToolUseBlockParam

type ToolUseBlockParam struct {
	ID    param.Field[string]                `json:"id,required"`
	Input param.Field[interface{}]           `json:"input,required"`
	Name  param.Field[string]                `json:"name,required"`
	Type  param.Field[ToolUseBlockParamType] `json:"type,required"`
}

func NewToolUseBlockParam

func NewToolUseBlockParam(id string, name string, input interface{}) ToolUseBlockParam

func (ToolUseBlockParam) MarshalJSON

func (r ToolUseBlockParam) MarshalJSON() (data []byte, err error)

type ToolUseBlockParamType

type ToolUseBlockParamType string
const (
	ToolUseBlockParamTypeToolUse ToolUseBlockParamType = "tool_use"
)

func (ToolUseBlockParamType) IsKnown

func (r ToolUseBlockParamType) IsKnown() bool

type ToolUseBlockType

type ToolUseBlockType string
const (
	ToolUseBlockTypeToolUse ToolUseBlockType = "tool_use"
)

func (ToolUseBlockType) IsKnown

func (r ToolUseBlockType) IsKnown() bool

type Usage

type Usage struct {
	// The number of input tokens which were used.
	InputTokens int64 `json:"input_tokens,required"`
	// The number of output tokens which were used.
	OutputTokens int64     `json:"output_tokens,required"`
	JSON         usageJSON `json:"-"`
}

func (*Usage) UnmarshalJSON

func (r *Usage) UnmarshalJSON(data []byte) (err error)

Directories

Path Synopsis
packages

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL