anthropic

package module
v2.14.1 Latest Latest
Warning

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

Go to latest
Published: Feb 26, 2025 License: Apache-2.0 Imports: 12 Imported by: 36

README

go-anthropic

Go Reference Go Report Card codecov Sanity check

Anthropic Claude API wrapper for Go (Unofficial).

This package has support for:

  • Completions
  • Streaming Completions
  • Messages
  • Streaming Messages
  • Message Batching
  • Vision and PDFs
  • Tool use (with computer use)
  • Prompt Caching
  • Token Counting

Installation

go get github.com/liushuangls/go-anthropic/v2

Currently, go-anthropic requires Go version 1.21 or greater.

Usage

Messages example usage:
package main

import (
	"errors"
	"fmt"

	"github.com/liushuangls/go-anthropic/v2"
)

func main() {
	client := anthropic.NewClient("your anthropic api key")
	resp, err := client.CreateMessages(context.Background(), anthropic.MessagesRequest{
		Model: anthropic.ModelClaude3Haiku20240307,
		Messages: []anthropic.Message{
			anthropic.NewUserTextMessage("What is your name?"),
		},
		MaxTokens: 1000,
	})
	if err != nil {
		var e *anthropic.APIError
		if errors.As(err, &e) {
			fmt.Printf("Messages error, type: %s, message: %s", e.Type, e.Message)
		} else {
			fmt.Printf("Messages error: %v\n", err)
		}
		return
	}
	fmt.Println(resp.Content[0].GetText())
}
Messages stream example usage:
package main

import (
	"errors"
	"fmt"

	"github.com/liushuangls/go-anthropic/v2"
)

func main() {
	client := anthropic.NewClient("your anthropic api key")
	resp, err := client.CreateMessagesStream(context.Background(), anthropic.MessagesStreamRequest{
		MessagesRequest: anthropic.MessagesRequest{
			Model: anthropic.ModelClaude3Haiku20240307,
			Messages: []anthropic.Message{
				anthropic.NewUserTextMessage("What is your name?"),
			},
			MaxTokens: 1000,
		},
		OnContentBlockDelta: func(data anthropic.MessagesEventContentBlockDeltaData) {
			fmt.Printf("Stream Content: %s\n", data.Delta.Text)
		},
	})
	if err != nil {
		var e *anthropic.APIError
		if errors.As(err, &e) {
			fmt.Printf("Messages stream error, type: %s, message: %s", e.Type, e.Message)
		} else {
			fmt.Printf("Messages stream error: %v\n", err)
		}
		return
	}
	fmt.Println(resp.Content[0].GetText())
}
Other examples:
Messages Vision example
package main

import (
	"errors"
	"fmt"

	"github.com/liushuangls/go-anthropic/v2"
)

func main() {
	client := anthropic.NewClient("your anthropic api key")

	imagePath := "xxx"
	imageMediaType := "image/jpeg"
	imageFile, err := os.Open(imagePath)
	if err != nil {
		panic(err)
	}
	imageData, err := io.ReadAll(imageFile)
	if err != nil {
		panic(err)
	}

	resp, err := client.CreateMessages(context.Background(), anthropic.MessagesRequest{
		Model: anthropic.ModelClaude3Opus20240229,
		Messages: []anthropic.Message{
			{
				Role: anthropic.RoleUser,
				Content: []anthropic.MessageContent{
					anthropic.NewImageMessageContent(
						anthropic.NewMessageContentSource(
							anthropic.MessagesContentSourceTypeBase64,
							imageMediaType,
							imageData,
						),
					),
					anthropic.NewTextMessageContent("Describe this image."),
				},
			},
		},
		MaxTokens: 1000,
	})
	if err != nil {
		var e *anthropic.APIError
		if errors.As(err, &e) {
			fmt.Printf("Messages error, type: %s, message: %s", e.Type, e.Message)
		} else {
			fmt.Printf("Messages error: %v\n", err)
		}
		return
	}
	fmt.Println(*resp.Content[0].GetText())
}
Messages Tool use example
package main

import (
	"context"
	"fmt"

	"github.com/liushuangls/go-anthropic/v2"
	"github.com/liushuangls/go-anthropic/v2/jsonschema"
)

func main() {
	client := anthropic.NewClient(
		"your anthropic api key",
	)

	request := anthropic.MessagesRequest{
		Model: anthropic.ModelClaude3Haiku20240307,
		Messages: []anthropic.Message{
			anthropic.NewUserTextMessage("What is the weather like in San Francisco?"),
		},
		MaxTokens: 1000,
		Tools: []anthropic.ToolDefinition{
			{
				Name:        "get_weather",
				Description: "Get the current weather in a given location",
				InputSchema: jsonschema.Definition{
					Type: jsonschema.Object,
					Properties: map[string]jsonschema.Definition{
						"location": {
							Type:        jsonschema.String,
							Description: "The city and state, e.g. San Francisco, CA",
						},
						"unit": {
							Type:        jsonschema.String,
							Enum:        []string{"celsius", "fahrenheit"},
							Description: "The unit of temperature, either 'celsius' or 'fahrenheit'",
						},
					},
					Required: []string{"location"},
				},
			},
		},
	}

	resp, err := client.CreateMessages(context.Background(), request)
	if err != nil {
		panic(err)
	}

	request.Messages = append(request.Messages, anthropic.Message{
		Role:    anthropic.RoleAssistant,
		Content: resp.Content,
	})

	var toolUse *anthropic.MessageContentToolUse

	for _, c := range resp.Content {
		if c.Type == anthropic.MessagesContentTypeToolUse {
			toolUse = c.MessageContentToolUse
		}
	}

	if toolUse == nil {
		panic("tool use not found")
	}

	request.Messages = append(request.Messages, anthropic.NewToolResultsMessage(toolUse.ID, "65 degrees", false))

	resp, err = client.CreateMessages(context.Background(), request)
	if err != nil {
		panic(err)
	}
	fmt.Printf("Response: %+v\n", resp)
}
Prompt Caching

doc: https://docs.anthropic.com/en/docs/build-with-claude/prompt-caching

package main

import (
	"context"
	"errors"
	"fmt"

	"github.com/liushuangls/go-anthropic/v2"
)

func main() {
	client := anthropic.NewClient(
		"your anthropic api key",
		anthropic.WithBetaVersion(anthropic.BetaPromptCaching20240731),
	)

	resp, err := client.CreateMessages(
		context.Background(),
		anthropic.MessagesRequest{
			Model: anthropic.ModelClaude3Haiku20240307,
			MultiSystem: []anthropic.MessageSystemPart{
				{
					Type: "text",
					Text: "You are an AI assistant tasked with analyzing literary works. Your goal is to provide insightful commentary on themes, characters, and writing style.",
				},
				{
					Type: "text",
					Text: "<the entire contents of Pride and Prejudice>",
					CacheControl: &anthropic.MessageCacheControl{
						Type: anthropic.CacheControlTypeEphemeral,
					},
				},
			},
			Messages: []anthropic.Message{
				anthropic.NewUserTextMessage("Analyze the major themes in Pride and Prejudice.")
			},
			MaxTokens: 1000,
	})
	if err != nil {
		var e *anthropic.APIError
		if errors.As(err, &e) {
			fmt.Printf("Messages error, type: %s, message: %s", e.Type, e.Message)
		} else {
			fmt.Printf("Messages error: %v\n", err)
		}
		return
	}
	fmt.Printf("Usage: %+v\n", resp.Usage)
	fmt.Println(resp.Content[0].GetText())
}
VertexAI example If you are using a Google Credentials file, you can use the following code to create a client:
package main

import (
	"context"
	"errors"
	"fmt"
	"os"

	"github.com/liushuangls/go-anthropic/v2"
	"golang.org/x/oauth2/google"
)

func main() {
	credBytes, err := os.ReadFile("<path to your credentials file>")
	if err != nil {
		fmt.Println("Error reading file")
		return
	}

	ts, err := google.JWTAccessTokenSourceWithScope(credBytes, "https://www.googleapis.com/auth/cloud-platform", "https://www.googleapis.com/auth/cloud-platform.read-only")
	if err != nil {
		fmt.Println("Error creating token source")
		return
	}

	// use JWTAccessTokenSourceWithScope
	token, err := ts.Token()
	if err != nil {
		fmt.Println("Error getting token")
		return
	}

	fmt.Println(token.AccessToken)

	client := anthropic.NewClient(token.AccessToken, anthropic.WithVertexAI("<YOUR PROJECTID>", "<YOUR LOCATION>"))

	resp, err := client.CreateMessagesStream(context.Background(), anthropic.MessagesStreamRequest{
		MessagesRequest: anthropic.MessagesRequest{
			Model: anthropic.ModelClaude3Haiku20240307,
			Messages: []anthropic.Message{
				anthropic.NewUserTextMessage("What is your name?"),
			},
			MaxTokens: 1000,
		},
		OnContentBlockDelta: func(data anthropic.MessagesEventContentBlockDeltaData) {
			fmt.Printf("Stream Content: %s\n", *data.Delta.Text)
		},
	})
	if err != nil {
		var e *anthropic.APIError
		if errors.As(err, &e) {
			fmt.Printf("Messages stream error, type: %s, message: %s", e.Type, e.Message)
		} else {
			fmt.Printf("Messages stream error: %v\n", err)
		}
		return
	}
	fmt.Println(resp.Content[0].GetText())
}
Message Batching

doc: https://docs.anthropic.com/en/docs/build-with-claude/message-batches

package main

import (
	"context"
	"errors"
	"fmt"
	"os"

	"github.com/liushuangls/go-anthropic/v2"
)

func main() {
	client := anthropic.NewClient(
		"your anthropic api key",
		anthropic.WithBetaVersion(anthropic.BetaMessageBatches20240924),
	)

	resp, err := client.CreateBatch(context.Background(),
		anthropic.BatchRequest{
			Requests: []anthropic.InnerRequests{
				{
					CustomId: myId,
					Params: anthropic.MessagesRequest{
						Model: anthropic.ModelClaude3Haiku20240307,
						MultiSystem: anthropic.NewMultiSystemMessages(
							"you are an assistant",
							"you are snarky",
						),
						MaxTokens: 10,
						Messages: []anthropic.Message{
							anthropic.NewUserTextMessage("What is your name?"),
							anthropic.NewAssistantTextMessage("My name is Claude."),
							anthropic.NewUserTextMessage("What is your favorite color?"),
						},
					},
				},
			},
		},
	)
	if err != nil {
		var e *anthropic.APIError
		if errors.As(err, &e) {
			fmt.Printf("Messages error, type: %s, message: %s", e.Type, e.Message)
		} else {
			fmt.Printf("Messages error: %v\n", err)
		}
		return
	}
	fmt.Println(resp)


	retrieveResp, err := client.RetrieveBatch(ctx, resp.Id)
	if err != nil {
		var e *anthropic.APIError
		if errors.As(err, &e) {
			fmt.Printf("Messages error, type: %s, message: %s", e.Type, e.Message)
		} else {
			fmt.Printf("Messages error: %v\n", err)
		}
		return
	}
	fmt.Println(retrieveResp)

	resultResp, err := client.RetrieveBatchResults(ctx, "batch_id_your-batch-here")
	if err != nil {
		var e *anthropic.APIError
		if errors.As(err, &e) {
			fmt.Printf("Messages error, type: %s, message: %s", e.Type, e.Message)
		} else {
			fmt.Printf("Messages error: %v\n", err)
		}
		return
	}
	fmt.Println(resultResp)


	listResp, err := client.ListBatches(ctx, anthropic.ListBatchesRequest{})
	if err != nil {
		var e *anthropic.APIError
		if errors.As(err, &e) {
			fmt.Printf("Messages error, type: %s, message: %s", e.Type, e.Message)
		} else {
			fmt.Printf("Messages error: %v\n", err)
		}
		return
	}
	fmt.Println(listResp)


	cancelResp, err := client.CancelBatch(ctx, "batch_id_your-batch-here")
	if err != nil {
		t.Fatalf("CancelBatch error: %s", err)
	}
	fmt.Println(cancelResp)
Token Counting example

doc: (https://docs.anthropic.com/en/docs/build-with-claude/token-counting)[https://docs.anthropic.com/en/docs/build-with-claude/token-counting]

// TODO: add example!
Beta features

Anthropic provides several beta features that can be enabled using the following beta version identifiers:

Beta Version Identifier Code Constant Description
tools-2024-04-04 BetaTools20240404 Initial tools beta
tools-2024-05-16 BetaTools20240516 Updated tools beta
prompt-caching-2024-07-31 BetaPromptCaching20240731 Prompt caching beta
message-batches-2024-09-24 BetaMessageBatches20240924 Message batching beta
token-counting-2024-11-01 BetaTokenCounting20241101 Token counting beta
max-tokens-3-5-sonnet-2024-07-15 BetaMaxTokens35Sonnet20240715 Max tokens beta for Sonnet model
computer-use-2024-10-22 BetaComputerUse20241022 Computer use beta
Supported models

The following models are supported by go-anthropic. These models are also available for use on Google's Vertex AI platform as well.

Model Name Model String
ModelClaude2Dot0 "claude-2.0"
ModelClaude2Dot1 "claude-2.1"
ModelClaude3Opus20240229 "claude-3-opus-20240229"
ModelClaude3Sonnet20240229 "claude-3-sonnet-20240229"
ModelClaude3Dot5Sonnet20240620 "claude-3-5-sonnet-20240620"
ModelClaude3Dot5Sonnet20241022 "claude-3-5-sonnet-20241022"
ModelClaude3Dot5SonnetLatest "claude-3-5-sonnet-latest"
ModelClaude3Haiku20240307 "claude-3-haiku-20240307"
ModelClaude3Dot5HaikuLatest "claude-3-5-haiku-latest"
ModelClaude3Dot5Haiku20241022 "claude-3-5-haiku-20241022"
Other Enums

Two exported enums are additionally provided:

  • RoleUser = "user": Input role type for user messages
  • RoleAssistant = "assistant": Input role type for assistant/Claude messages

Acknowledgments

The following project had particular influence on go-anthropic's design.

Additionally, we thank anthropic for providing the API and documentation.

License

go-anthropic is licensed under the Apache License, Version 2.0. See LICENSE for the full license text.

Documentation

Index

Constants

View Source
const (
	MessagesContentSourceTypeBase64 = "base64"
)

Variables

View Source
var (
	ErrSteamingNotSupportTools = errors.New("streaming is not yet supported tools")
)
View Source
var (
	ErrTooManyEmptyStreamMessages = errors.New("stream has sent too many empty messages")
)

Functions

This section is empty.

Types

type APIError

type APIError struct {
	Type    ErrType `json:"type"`
	Message string  `json:"message"`
}

APIError provides error information returned by the Anthropic API.

func (*APIError) Error

func (e *APIError) Error() string

func (*APIError) IsApiErr

func (e *APIError) IsApiErr() bool

func (*APIError) IsAuthenticationErr

func (e *APIError) IsAuthenticationErr() bool

func (*APIError) IsInvalidRequestErr

func (e *APIError) IsInvalidRequestErr() bool

func (*APIError) IsNotFoundErr

func (e *APIError) IsNotFoundErr() bool

func (*APIError) IsOverloadedErr

func (e *APIError) IsOverloadedErr() bool

func (*APIError) IsPermissionErr

func (e *APIError) IsPermissionErr() bool

func (*APIError) IsRateLimitErr

func (e *APIError) IsRateLimitErr() bool

func (*APIError) IsTooLargeErr added in v2.4.1

func (e *APIError) IsTooLargeErr() bool

type APIVersion added in v2.8.0

type APIVersion string
const (
	APIVersion20230601       APIVersion = "2023-06-01"
	APIVersionVertex20231016 APIVersion = "vertex-2023-10-16"
)

type ApiKeyFunc added in v2.12.0

type ApiKeyFunc func() string

type BatchId added in v2.9.0

type BatchId string

type BatchRequest added in v2.9.0

type BatchRequest struct {
	Requests []InnerRequests `json:"requests"`
}

While in beta, batches may contain up to 10,000 requests and be up to 32 MB in total size.

type BatchRespCore added in v2.9.0

type BatchRespCore struct {
	Id                BatchId           `json:"id"`
	Type              BatchResponseType `json:"type"`
	ProcessingStatus  ProcessingStatus  `json:"processing_status"`
	RequestCounts     RequestCounts     `json:"request_counts"`
	EndedAt           *time.Time        `json:"ended_at"`
	CreatedAt         time.Time         `json:"created_at"`
	ExpiresAt         time.Time         `json:"expires_at"`
	ArchivedAt        *time.Time        `json:"archived_at"`
	CancelInitiatedAt *time.Time        `json:"cancel_initiated_at"`
	ResultsUrl        *string           `json:"results_url"`
}

type BatchResponse added in v2.9.0

type BatchResponse struct {
	BatchRespCore
	// contains filtered or unexported fields
}

All times returned in RFC 3339

func (*BatchResponse) GetRateLimitHeaders added in v2.9.0

func (h *BatchResponse) GetRateLimitHeaders() (RateLimitHeaders, error)

func (*BatchResponse) Header added in v2.9.0

func (h *BatchResponse) Header() http.Header

func (*BatchResponse) SetHeader added in v2.9.0

func (h *BatchResponse) SetHeader(header http.Header)

type BatchResponseType added in v2.9.0

type BatchResponseType string
const (
	BatchResponseTypeMessageBatch BatchResponseType = "message_batch"
)

type BatchResult added in v2.9.0

type BatchResult struct {
	CustomId string          `json:"custom_id"`
	Result   BatchResultCore `json:"result"`
}

type BatchResultCore added in v2.9.0

type BatchResultCore struct {
	Type   ResultType       `json:"type"`
	Result MessagesResponse `json:"message"`
}

type BetaVersion added in v2.8.0

type BetaVersion string
const (
	BetaTools20240404             BetaVersion = "tools-2024-04-04"
	BetaTools20240516             BetaVersion = "tools-2024-05-16"
	BetaPromptCaching20240731     BetaVersion = "prompt-caching-2024-07-31"
	BetaMessageBatches20240924    BetaVersion = "message-batches-2024-09-24"
	BetaTokenCounting20241101     BetaVersion = "token-counting-2024-11-01"
	BetaMaxTokens35Sonnet20240715 BetaVersion = "max-tokens-3-5-sonnet-2024-07-15"
	BetaComputerUse20241022       BetaVersion = "computer-use-2024-10-22"
	BetaOutput128k20250219        BetaVersion = "output-128k-2025-02-19"
)

type CacheControlType added in v2.6.0

type CacheControlType string
const (
	CacheControlTypeEphemeral CacheControlType = "ephemeral"
)

type ChatRole added in v2.7.0

type ChatRole string
const (
	RoleUser      ChatRole = "user"
	RoleAssistant ChatRole = "assistant"
)

type Client

type Client struct {
	// contains filtered or unexported fields
}

func NewClient

func NewClient(apiKey string, opts ...ClientOption) *Client

NewClient create new Anthropic API client

func (*Client) CancelBatch added in v2.9.0

func (c *Client) CancelBatch(
	ctx context.Context,
	batchId BatchId,
) (*BatchResponse, error)

func (*Client) CountTokens added in v2.10.0

func (c *Client) CountTokens(
	ctx context.Context,
	request MessagesRequest,
) (response CountTokensResponse, err error)

func (*Client) CreateBatch added in v2.9.0

func (c *Client) CreateBatch(
	ctx context.Context,
	request BatchRequest,
) (*BatchResponse, error)

func (*Client) CreateComplete

func (c *Client) CreateComplete(
	ctx context.Context,
	request CompleteRequest,
) (response CompleteResponse, err error)

func (*Client) CreateCompleteStream

func (c *Client) CreateCompleteStream(
	ctx context.Context,
	request CompleteStreamRequest,
) (response CompleteResponse, err error)

func (*Client) CreateMessages

func (c *Client) CreateMessages(
	ctx context.Context,
	request MessagesRequest,
) (response MessagesResponse, err error)

func (*Client) CreateMessagesStream

func (c *Client) CreateMessagesStream(
	ctx context.Context,
	request MessagesStreamRequest,
) (response MessagesResponse, err error)

func (*Client) ListBatches added in v2.9.0

func (c *Client) ListBatches(
	ctx context.Context,
	lBatchReq ListBatchesRequest,
) (*ListBatchesResponse, error)

func (*Client) RetrieveBatch added in v2.9.0

func (c *Client) RetrieveBatch(
	ctx context.Context,
	batchId BatchId,
) (*BatchResponse, error)

func (*Client) RetrieveBatchResults added in v2.9.0

func (c *Client) RetrieveBatchResults(
	ctx context.Context,
	batchId BatchId,
) (*RetrieveBatchResultsResponse, error)

type ClientAdapter added in v2.12.0

type ClientAdapter interface {
	// Translate provider specific errors.  Responds with an error and a boolean indicating if the error has been successfully parsed.
	TranslateError(resp *http.Response, body []byte) (error, bool)
	// Prepare the request for the provider and return the full URL
	PrepareRequest(c *Client, method, urlSuffix string, body any) (string, error)
	// Set the request headers for the provider
	SetRequestHeaders(c *Client, req *http.Request) error
}

ClientAdapter is an interface that defines the methods that allow use of the anthropic API with different providers.

type ClientConfig

type ClientConfig struct {
	BaseURL     string
	APIVersion  APIVersion
	BetaVersion []BetaVersion
	HTTPClient  *http.Client

	EmptyMessagesLimit uint

	Adapter ClientAdapter
	// contains filtered or unexported fields
}

ClientConfig is a configuration of a client.

func (*ClientConfig) GetApiKey added in v2.12.0

func (c *ClientConfig) GetApiKey() string

type ClientOption

type ClientOption func(c *ClientConfig)

func WithAPIVersion

func WithAPIVersion(apiVersion APIVersion) ClientOption

func WithApiKeyFunc added in v2.12.0

func WithApiKeyFunc(apiKeyFunc ApiKeyFunc) ClientOption

func WithBaseURL

func WithBaseURL(baseUrl string) ClientOption

func WithBetaVersion

func WithBetaVersion(betaVersion ...BetaVersion) ClientOption

func WithEmptyMessagesLimit

func WithEmptyMessagesLimit(limit uint) ClientOption

func WithHTTPClient

func WithHTTPClient(cli *http.Client) ClientOption

func WithVertexAI added in v2.12.0

func WithVertexAI(projectID string, location string) ClientOption

type CompleteEvent

type CompleteEvent string
const (
	CompleteEventError      CompleteEvent = "error"
	CompleteEventCompletion CompleteEvent = "completion"
	CompleteEventPing       CompleteEvent = "ping"
)

type CompleteRequest

type CompleteRequest struct {
	Model             Model  `json:"model"`
	Prompt            string `json:"prompt"`
	MaxTokensToSample int    `json:"max_tokens_to_sample"`

	StopSequences []string       `json:"stop_sequences,omitempty"`
	Temperature   *float32       `json:"temperature,omitempty"`
	TopP          *float32       `json:"top_p,omitempty"`
	TopK          *int           `json:"top_k,omitempty"`
	MetaData      map[string]any `json:"meta_data,omitempty"`
	Stream        bool           `json:"stream,omitempty"`
}

func (*CompleteRequest) SetTemperature

func (c *CompleteRequest) SetTemperature(t float32)

func (*CompleteRequest) SetTopK

func (c *CompleteRequest) SetTopK(k int)

func (*CompleteRequest) SetTopP

func (c *CompleteRequest) SetTopP(p float32)

type CompleteResponse

type CompleteResponse struct {
	Type       string `json:"type"`
	ID         string `json:"id"`
	Completion string `json:"completion"`
	// possible values are: stop_sequence、max_tokens、null
	StopReason string `json:"stop_reason"`
	Model      Model  `json:"model"`
	// contains filtered or unexported fields
}

func (*CompleteResponse) GetRateLimitHeaders added in v2.3.0

func (h *CompleteResponse) GetRateLimitHeaders() (RateLimitHeaders, error)

func (*CompleteResponse) Header added in v2.1.0

func (h *CompleteResponse) Header() http.Header

func (*CompleteResponse) SetHeader added in v2.1.0

func (h *CompleteResponse) SetHeader(header http.Header)

type CompleteStreamPingData

type CompleteStreamPingData struct {
	Type string `json:"type"`
}

type CompleteStreamRequest

type CompleteStreamRequest struct {
	CompleteRequest

	OnCompletion func(CompleteResponse)       `json:"-"`
	OnPing       func(CompleteStreamPingData) `json:"-"`
	OnError      func(ErrorResponse)          `json:"-"`
}

type CountTokensResponse added in v2.10.0

type CountTokensResponse struct {
	InputTokens int `json:"input_tokens"`
	// contains filtered or unexported fields
}

func (*CountTokensResponse) GetRateLimitHeaders added in v2.10.0

func (h *CountTokensResponse) GetRateLimitHeaders() (RateLimitHeaders, error)

func (*CountTokensResponse) Header added in v2.10.0

func (h *CountTokensResponse) Header() http.Header

func (*CountTokensResponse) SetHeader added in v2.10.0

func (h *CountTokensResponse) SetHeader(header http.Header)

type DefaultAdapter added in v2.12.0

type DefaultAdapter struct {
}

func (*DefaultAdapter) PrepareRequest added in v2.12.0

func (v *DefaultAdapter) PrepareRequest(
	c *Client,
	method string,
	urlSuffix string,
	body any,
) (string, error)

func (*DefaultAdapter) SetRequestHeaders added in v2.12.0

func (v *DefaultAdapter) SetRequestHeaders(c *Client, req *http.Request) error

func (*DefaultAdapter) TranslateError added in v2.12.0

func (v *DefaultAdapter) TranslateError(resp *http.Response, body []byte) (error, bool)

type ErrType

type ErrType string
const (
	// ErrTypeInvalidRequest There was an issue with the format or content of your request.
	ErrTypeInvalidRequest ErrType = "invalid_request_error"
	// ErrTypeAuthentication There's an issue with your API key.
	ErrTypeAuthentication ErrType = "authentication_error"
	// ErrTypePermission Your API key does not have permission to use the specified resource.
	ErrTypePermission ErrType = "permission_error"
	// ErrTypeNotFound The requested resource was not found.
	ErrTypeNotFound ErrType = "not_found_error"
	// ErrTypeTooLarge Request exceeds the maximum allowed number of bytes.
	ErrTypeTooLarge ErrType = "request_too_large"
	// ErrTypeRateLimit Your account has hit a rate limit.
	ErrTypeRateLimit ErrType = "rate_limit_error"
	// ErrTypeApi An unexpected error has occurred internal to Anthropic's systems.
	ErrTypeApi ErrType = "api_error"
	// ErrTypeOverloaded Anthropic's API is temporarily overloaded.
	ErrTypeOverloaded ErrType = "overloaded_error"
)

type ErrorResponse

type ErrorResponse struct {
	Type  string    `json:"type"`
	Error *APIError `json:"error,omitempty"`
}

type InnerRequests added in v2.9.0

type InnerRequests struct {
	CustomId string          `json:"custom_id"`
	Params   MessagesRequest `json:"params"`
}

type ListBatchesRequest added in v2.9.0

type ListBatchesRequest struct {
	BeforeId *string `json:"before_id,omitempty"`
	AfterId  *string `json:"after_id,omitempty"`
	Limit    *int    `json:"limit,omitempty"`
}

type ListBatchesResponse added in v2.9.0

type ListBatchesResponse struct {
	Data    []BatchRespCore `json:"data"`
	HasMore bool            `json:"has_more"`
	FirstId *BatchId        `json:"first_id"`
	LastId  *BatchId        `json:"last_id"`
	// contains filtered or unexported fields
}

func (*ListBatchesResponse) GetRateLimitHeaders added in v2.9.0

func (h *ListBatchesResponse) GetRateLimitHeaders() (RateLimitHeaders, error)

func (*ListBatchesResponse) Header added in v2.9.0

func (h *ListBatchesResponse) Header() http.Header

func (*ListBatchesResponse) SetHeader added in v2.9.0

func (h *ListBatchesResponse) SetHeader(header http.Header)

type Message

type Message struct {
	Role    ChatRole         `json:"role"`
	Content []MessageContent `json:"content"`
}

func NewAssistantTextMessage

func NewAssistantTextMessage(text string) Message

func NewToolResultsMessage

func NewToolResultsMessage(toolUseID, content string, isError bool) Message

func NewUserTextMessage

func NewUserTextMessage(text string) Message

func (Message) GetFirstContent

func (m Message) GetFirstContent() MessageContent

type MessageCacheControl added in v2.6.0

type MessageCacheControl struct {
	Type CacheControlType `json:"type"`
}

type MessageContent

type MessageContent struct {
	Type MessagesContentType `json:"type"`

	Text *string `json:"text,omitempty"`

	Source *MessageContentSource `json:"source,omitempty"`

	*MessageContentToolResult

	*MessageContentToolUse

	PartialJson *string `json:"partial_json,omitempty"`

	CacheControl *MessageCacheControl `json:"cache_control,omitempty"`

	*MessageContentThinking

	*MessageContentRedactedThinking
}

func NewDocumentMessageContent added in v2.11.0

func NewDocumentMessageContent(source MessageContentSource) MessageContent

func NewImageMessageContent

func NewImageMessageContent(source MessageContentSource) MessageContent

func NewTextMessageContent

func NewTextMessageContent(text string) MessageContent

func NewToolResultMessageContent

func NewToolResultMessageContent(toolUseID, content string, isError bool) MessageContent

func NewToolUseMessageContent

func NewToolUseMessageContent(toolUseID, name string, input json.RawMessage) MessageContent

func (*MessageContent) ConcatText

func (m *MessageContent) ConcatText(s string)

func (*MessageContent) GetText

func (m *MessageContent) GetText() string

func (*MessageContent) MergeContentDelta added in v2.2.0

func (m *MessageContent) MergeContentDelta(mc MessageContent)

func (*MessageContent) SetCacheControl added in v2.6.0

func (m *MessageContent) SetCacheControl(ts ...CacheControlType)

type MessageContentRedactedThinking added in v2.14.0

type MessageContentRedactedThinking struct {
	Data string `json:"data,omitempty"`
}

type MessageContentSource added in v2.11.0

type MessageContentSource struct {
	Type      MessagesContentSourceType `json:"type"`
	MediaType string                    `json:"media_type"`
	Data      any                       `json:"data"`
}

func NewMessageContentSource added in v2.11.0

func NewMessageContentSource(
	sourceType MessagesContentSourceType,
	mediaType string,
	data any,
) MessageContentSource

type MessageContentThinking added in v2.14.0

type MessageContentThinking struct {
	Thinking  string `json:"thinking,omitempty"`
	Signature string `json:"signature,omitempty"`
}

type MessageContentToolResult

type MessageContentToolResult struct {
	ToolUseID *string          `json:"tool_use_id,omitempty"`
	Content   []MessageContent `json:"content,omitempty"`
	IsError   *bool            `json:"is_error,omitempty"`
}

func NewMessageContentToolResult

func NewMessageContentToolResult(
	toolUseID, content string,
	isError bool,
) *MessageContentToolResult

type MessageContentToolUse

type MessageContentToolUse struct {
	ID    string          `json:"id,omitempty"`
	Name  string          `json:"name,omitempty"`
	Input json.RawMessage `json:"input,omitempty"`
}

func NewMessageContentToolUse added in v2.7.0

func NewMessageContentToolUse(
	toolUseId, name string,
	input json.RawMessage,
) *MessageContentToolUse

func (*MessageContentToolUse) UnmarshalInput added in v2.2.0

func (c *MessageContentToolUse) UnmarshalInput(v any) error

type MessageSystemPart added in v2.6.0

type MessageSystemPart struct {
	Type         string               `json:"type"`
	Text         string               `json:"text"`
	CacheControl *MessageCacheControl `json:"cache_control,omitempty"`
}

func NewMultiSystemMessages added in v2.7.0

func NewMultiSystemMessages(texts ...string) []MessageSystemPart

func NewSystemMessagePart added in v2.7.0

func NewSystemMessagePart(text string) MessageSystemPart

type MessagesContentSourceType added in v2.11.0

type MessagesContentSourceType string

type MessagesContentType

type MessagesContentType string
const (
	MessagesContentTypeText             MessagesContentType = "text"
	MessagesContentTypeTextDelta        MessagesContentType = "text_delta"
	MessagesContentTypeImage            MessagesContentType = "image"
	MessagesContentTypeToolResult       MessagesContentType = "tool_result"
	MessagesContentTypeToolUse          MessagesContentType = "tool_use"
	MessagesContentTypeInputJsonDelta   MessagesContentType = "input_json_delta"
	MessagesContentTypeDocument         MessagesContentType = "document"
	MessagesContentTypeThinking         MessagesContentType = "thinking"
	MessagesContentTypeThinkingDelta    MessagesContentType = "thinking_delta"
	MessagesContentTypeSignatureDelta   MessagesContentType = "signature_delta"
	MessagesContentTypeRedactedThinking MessagesContentType = "redacted_thinking"
)

type MessagesEvent

type MessagesEvent string

MessagesEvent docs: https://docs.anthropic.com/claude/reference/messages-streaming

const (
	MessagesEventError             MessagesEvent = "error"
	MessagesEventMessageStart      MessagesEvent = "message_start"
	MessagesEventContentBlockStart MessagesEvent = "content_block_start"
	MessagesEventPing              MessagesEvent = "ping"
	MessagesEventContentBlockDelta MessagesEvent = "content_block_delta"
	MessagesEventContentBlockStop  MessagesEvent = "content_block_stop"
	MessagesEventMessageDelta      MessagesEvent = "message_delta"
	MessagesEventMessageStop       MessagesEvent = "message_stop"
)

type MessagesEventContentBlockDeltaData

type MessagesEventContentBlockDeltaData struct {
	Type  string         `json:"type"`
	Index int            `json:"index"`
	Delta MessageContent `json:"delta"`
}

type MessagesEventContentBlockStartData

type MessagesEventContentBlockStartData struct {
	Type         MessagesEvent  `json:"type"`
	Index        int            `json:"index"`
	ContentBlock MessageContent `json:"content_block"`
}

type MessagesEventContentBlockStopData

type MessagesEventContentBlockStopData struct {
	Type  string `json:"type"`
	Index int    `json:"index"`
}

type MessagesEventMessageDeltaData

type MessagesEventMessageDeltaData struct {
	Type  string           `json:"type"`
	Delta MessagesResponse `json:"delta"`
	Usage MessagesUsage    `json:"usage"`
}

type MessagesEventMessageStartData

type MessagesEventMessageStartData struct {
	Type    MessagesEvent    `json:"type"`
	Message MessagesResponse `json:"message"`
}

type MessagesEventMessageStopData

type MessagesEventMessageStopData struct {
	Type string `json:"type"`
}

type MessagesEventPingData

type MessagesEventPingData struct {
	Type string `json:"type"`
}

type MessagesRequest

type MessagesRequest struct {
	Model            Model     `json:"model,omitempty"`
	AnthropicVersion string    `json:"anthropic_version,omitempty"`
	Messages         []Message `json:"messages"`
	MaxTokens        int       `json:"max_tokens,omitempty"`

	System        string              `json:"-"`
	MultiSystem   []MessageSystemPart `json:"-"`
	Metadata      map[string]any      `json:"metadata,omitempty"`
	StopSequences []string            `json:"stop_sequences,omitempty"`
	Stream        bool                `json:"stream,omitempty"`
	Temperature   *float32            `json:"temperature,omitempty"`
	TopP          *float32            `json:"top_p,omitempty"`
	TopK          *int                `json:"top_k,omitempty"`
	Tools         []ToolDefinition    `json:"tools,omitempty"`
	ToolChoice    *ToolChoice         `json:"tool_choice,omitempty"`
	Thinking      *Thinking           `json:"thinking,omitempty"`
}

func (MessagesRequest) GetModel added in v2.12.0

func (m MessagesRequest) GetModel() Model

func (*MessagesRequest) IsStreaming added in v2.12.0

func (m *MessagesRequest) IsStreaming() bool

func (MessagesRequest) MarshalJSON added in v2.6.0

func (m MessagesRequest) MarshalJSON() ([]byte, error)

func (*MessagesRequest) SetAnthropicVersion added in v2.12.0

func (m *MessagesRequest) SetAnthropicVersion(version APIVersion)

func (*MessagesRequest) SetTemperature

func (m *MessagesRequest) SetTemperature(t float32)

func (*MessagesRequest) SetTopK

func (m *MessagesRequest) SetTopK(k int)

func (*MessagesRequest) SetTopP

func (m *MessagesRequest) SetTopP(p float32)

type MessagesResponse

type MessagesResponse struct {
	ID           string               `json:"id"`
	Type         MessagesResponseType `json:"type"`
	Role         ChatRole             `json:"role"`
	Content      []MessageContent     `json:"content"`
	Model        Model                `json:"model"`
	StopReason   MessagesStopReason   `json:"stop_reason"`
	StopSequence string               `json:"stop_sequence"`
	Usage        MessagesUsage        `json:"usage"`
	// contains filtered or unexported fields
}

func (MessagesResponse) GetFirstContentText

func (m MessagesResponse) GetFirstContentText() string

GetFirstContentText get Content[0].Text avoid panic

func (*MessagesResponse) GetRateLimitHeaders added in v2.3.0

func (h *MessagesResponse) GetRateLimitHeaders() (RateLimitHeaders, error)

func (*MessagesResponse) Header added in v2.1.0

func (h *MessagesResponse) Header() http.Header

func (*MessagesResponse) SetHeader added in v2.1.0

func (h *MessagesResponse) SetHeader(header http.Header)

type MessagesResponseType

type MessagesResponseType string
const (
	MessagesResponseTypeMessage MessagesResponseType = "message"
	MessagesResponseTypeError   MessagesResponseType = "error"
)

type MessagesStopReason

type MessagesStopReason string
const (
	MessagesStopReasonEndTurn      MessagesStopReason = "end_turn"
	MessagesStopReasonMaxTokens    MessagesStopReason = "max_tokens"
	MessagesStopReasonStopSequence MessagesStopReason = "stop_sequence"
	MessagesStopReasonToolUse      MessagesStopReason = "tool_use"
)

type MessagesStreamRequest

type MessagesStreamRequest struct {
	MessagesRequest

	OnError             func(ErrorResponse)                                     `json:"-"`
	OnPing              func(MessagesEventPingData)                             `json:"-"`
	OnMessageStart      func(MessagesEventMessageStartData)                     `json:"-"`
	OnContentBlockStart func(MessagesEventContentBlockStartData)                `json:"-"`
	OnContentBlockDelta func(MessagesEventContentBlockDeltaData)                `json:"-"`
	OnContentBlockStop  func(MessagesEventContentBlockStopData, MessageContent) `json:"-"`
	OnMessageDelta      func(MessagesEventMessageDeltaData)                     `json:"-"`
	OnMessageStop       func(MessagesEventMessageStopData)                      `json:"-"`
}

type MessagesUsage

type MessagesUsage struct {
	InputTokens  int `json:"input_tokens"`
	OutputTokens int `json:"output_tokens"`

	// The number of tokens written to the cache when creating a new entry.
	CacheCreationInputTokens int `json:"cache_creation_input_tokens,omitempty"`
	// The number of tokens retrieved from the cache for associated request.
	CacheReadInputTokens int `json:"cache_read_input_tokens,omitempty"`
}

type Model added in v2.7.0

type Model string
const (
	ModelClaude2Dot0               Model = "claude-2.0"
	ModelClaude2Dot1               Model = "claude-2.1"
	ModelClaude3Opus20240229       Model = "claude-3-opus-20240229"
	ModelClaude3Sonnet20240229     Model = "claude-3-sonnet-20240229"
	ModelClaude3Dot5Sonnet20240620 Model = "claude-3-5-sonnet-20240620"
	ModelClaude3Dot5Sonnet20241022 Model = "claude-3-5-sonnet-20241022"
	ModelClaude3Dot5SonnetLatest   Model = "claude-3-5-sonnet-latest"
	ModelClaude3Haiku20240307      Model = "claude-3-haiku-20240307"
	ModelClaude3Dot5HaikuLatest    Model = "claude-3-5-haiku-latest"
	ModelClaude3Dot5Haiku20241022  Model = "claude-3-5-haiku-20241022"
	ModelClaude3Dot7SonnetLatest   Model = "claude-3-7-sonnet-latest"
	ModelClaude3Dot7Sonnet20250219 Model = "claude-3-7-sonnet-20250219"
)

type ProcessingStatus added in v2.9.0

type ProcessingStatus string
const (
	ProcessingStatusInProgress ProcessingStatus = "in_progress"
	ProcessingStatusCanceling  ProcessingStatus = "canceling"
	ProcessingStatusEnded      ProcessingStatus = "ended"
)

type RateLimitHeaders added in v2.3.0

type RateLimitHeaders struct {
	// The maximum number of requests allowed within the rate limit window.
	RequestsLimit int `json:"anthropic-ratelimit-requests-limit"`
	// The number of requests remaining within the current rate limit window.
	RequestsRemaining int `json:"anthropic-ratelimit-requests-remaining"`
	// The time when the request rate limit window will reset, provided in RFC 3339 format.
	RequestsReset time.Time `json:"anthropic-ratelimit-requests-reset"`
	// The maximum number of tokens allowed within the rate limit window.
	TokensLimit int `json:"anthropic-ratelimit-tokens-limit"`
	// The number of tokens remaining, rounded to the nearest thousand, within the current rate limit window.
	TokensRemaining int `json:"anthropic-ratelimit-tokens-remaining"`
	// The time when the token rate limit window will reset, provided in RFC 3339 format.
	TokensReset time.Time `json:"anthropic-ratelimit-tokens-reset"`
	// The maximum number of input tokens allowed within any rate limit period.
	InputTokensLimit int `json:"anthropic-ratelimit-input-tokens-limit"`
	// The number of input tokens remaining (rounded to the nearest thousand) before being rate limited.
	InputTokensRemaining int `json:"anthropic-ratelimit-input-tokens-remaining"`
	// The time when the input token rate limit will be fully replenished, provided in RFC 3339 format.
	InputTokensReset time.Time `json:"anthropic-ratelimit-input-tokens-reset"`
	// The maximum number of output tokens allowed within any rate limit period.
	OutputTokensLimit int `json:"anthropic-ratelimit-output-tokens-limit"`
	// The number of output tokens remaining (rounded to the nearest thousand) before being rate limited.
	OutputTokensRemaining int `json:"anthropic-ratelimit-output-tokens-remaining"`
	// The time when the output token rate limit will be fully replenished, provided in RFC 3339 format.
	OutputTokensReset time.Time `json:"anthropic-ratelimit-output-tokens-reset"`
	// The number of seconds until the rate limit window resets.
	RetryAfter int `json:"retry-after"`
}

type RequestCounts added in v2.9.0

type RequestCounts struct {
	Processing int `json:"processing"`
	Succeeded  int `json:"succeeded"`
	Errored    int `json:"errored"`
	Canceled   int `json:"canceled"`
	Expired    int `json:"expired"`
}

type RequestError

type RequestError struct {
	StatusCode int
	Err        error
	Body       []byte
}

RequestError provides information about generic request errors.

func (*RequestError) Error

func (e *RequestError) Error() string

type Response added in v2.1.0

type Response interface {
	SetHeader(http.Header)
}

type ResultType added in v2.9.0

type ResultType string
const (
	ResultTypeSucceeded ResultType = "succeeded"
	ResultTypeErrored   ResultType = "errored"
	ResultTypeCanceled  ResultType = "canceled"
	ResultTypeExpired   ResultType = "expired"
)

type RetrieveBatchResultsResponse added in v2.9.0

type RetrieveBatchResultsResponse struct {
	Responses   []BatchResult
	RawResponse []byte
	// contains filtered or unexported fields
}

func (*RetrieveBatchResultsResponse) GetRateLimitHeaders added in v2.9.0

func (h *RetrieveBatchResultsResponse) GetRateLimitHeaders() (RateLimitHeaders, error)

func (*RetrieveBatchResultsResponse) Header added in v2.9.0

func (h *RetrieveBatchResultsResponse) Header() http.Header

func (*RetrieveBatchResultsResponse) SetHeader added in v2.9.0

func (h *RetrieveBatchResultsResponse) SetHeader(header http.Header)

type Thinking added in v2.14.0

type Thinking struct {
	Type ThinkingType `json:"type"`
	// Determines how many tokens Claude can use for its internal reasoning process. Larger budgets can enable more thorough analysis for complex problems, improving response quality.
	// Must be ≥1024 and less than max_tokens.
	BudgetTokens int `json:"budget_tokens"`
}

type ThinkingType added in v2.14.0

type ThinkingType string
const (
	ThinkingTypeEnabled  ThinkingType = "enabled"
	ThinkingTypeDisabled ThinkingType = "disabled"
)

type ToolChoice added in v2.2.0

type ToolChoice struct {
	// oneof: auto(default) any tool
	Type string `json:"type"`
	Name string `json:"name,omitempty"`
}

type ToolDefinition

type ToolDefinition struct {
	Name        string `json:"name"`
	Description string `json:"description,omitempty"`
	// InputSchema is an object describing the tool.
	// You can pass json.RawMessage to describe the schema,
	// or you can pass in a struct which serializes to the proper JSON schema.
	// The jsonschema package is provided for convenience, but you should
	// consider another specialized library if you require more complex schemas.
	InputSchema any `json:"input_schema,omitempty"`

	CacheControl *MessageCacheControl `json:"cache_control,omitempty"`

	// Type is required for Anthropic defined tools.
	Type string `json:"type,omitempty"`
	// DisplayWidthPx is a required parameter of the Computer Use tool.
	DisplayWidthPx int `json:"display_width_px,omitempty"`
	// DisplayHeightPx is a required parameter of the Computer Use tool.
	DisplayHeightPx int `json:"display_height_px,omitempty"`
	// DisplayNumber is an optional parameter of the Computer Use tool.
	DisplayNumber *int `json:"display_number,omitempty"`
}

func NewBashToolDefinition added in v2.13.0

func NewBashToolDefinition(name string) ToolDefinition

func NewComputerUseToolDefinition added in v2.13.0

func NewComputerUseToolDefinition(
	name string,
	displayWidthPx int,
	displayHeightPx int,
	displayNumber *int,
) ToolDefinition

func NewTextEditorToolDefinition added in v2.13.0

func NewTextEditorToolDefinition(name string) ToolDefinition

type VertexAIErrorResponse added in v2.12.0

type VertexAIErrorResponse struct {
	Error *VertexAPIError `json:"error,omitempty"`
}

type VertexAISupport added in v2.12.0

type VertexAISupport interface {
	GetModel() Model
	SetAnthropicVersion(APIVersion)
	IsStreaming() bool
}

VertexAISupport is an interface that is used to configure Vertex AI requests. The changes are defined here: https://docs.anthropic.com/en/api/claude-on-vertex-ai Model needs to be in the calling URL The version of the API is defined in the request body This interface allows the vertex ai changes to be contained in the client code, and not leak to each indivdual request definition.

type VertexAPIError added in v2.12.0

type VertexAPIError struct {
	Code    int                     `json:"code"`
	Message string                  `json:"message"`
	Status  string                  `json:"status"`
	Details []VertexAPIErrorDetails `json:"details"`
}

VertexAPIError provides error information returned by the Anthropic API.

func (*VertexAPIError) Error added in v2.12.0

func (e *VertexAPIError) Error() string

type VertexAPIErrorDetails added in v2.12.0

type VertexAPIErrorDetails struct {
	Type     string `json:"@type"`
	Reason   string `json:"reason"`
	Metadata struct {
		Method  string `json:"method"`
		Service string `json:"service"`
	} `json:"metadata"`
}

type VertexAdapter added in v2.12.0

type VertexAdapter struct {
}

func (*VertexAdapter) PrepareRequest added in v2.12.0

func (v *VertexAdapter) PrepareRequest(
	c *Client,
	method string,
	urlSuffix string,
	body any,
) (string, error)

func (*VertexAdapter) SetRequestHeaders added in v2.12.0

func (v *VertexAdapter) SetRequestHeaders(c *Client, req *http.Request) error

func (*VertexAdapter) TranslateError added in v2.12.0

func (v *VertexAdapter) TranslateError(resp *http.Response, body []byte) (error, bool)

Directories

Path Synopsis
internal
Package jsonschema provides very simple functionality for representing a JSON schema as a (nested) struct.
Package jsonschema provides very simple functionality for representing a JSON schema as a (nested) struct.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL
JackTT - Gopher 🇻🇳