anthropic

package
v2.2.5 Latest Latest
Warning

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

Go to latest
Published: Jun 25, 2024 License: Apache-2.0 Imports: 8 Imported by: 3

Documentation

Overview

Package client contains the HTTP client and related functionality for the anthropic package.

Index

Constants

View Source
const (
	// Constants for message event types
	MessageEventTypeMessageStart      MessageEventType = "message_start"
	MessageEventTypeContentBlockStart MessageEventType = "content_block_start"
	MessageEventTypePing              MessageEventType = "ping"
	MessageEventTypeContentBlockDelta MessageEventType = "content_block_delta"
	MessageEventTypeContentBlockStop  MessageEventType = "content_block_stop"
	MessageEventTypeMessageDelta      MessageEventType = "message_delta"
	MessageEventTypeMessageStop       MessageEventType = "message_stop"

	// Constants for completion event types
	CompletionEventTypeCompletion CompletionEventType = "completion"
	CompletionEventTypePing       CompletionEventType = "ping"
)
View Source
const (
	// AnthropicAPIVersion is the version of the Anthropics API that this client is compatible with.
	AnthropicAPIVersion = "2023-06-01"
	// AnthropicAPIMessagesBeta is the beta version of the Anthropics API that enables the messages endpoint.
	AnthropicAPIMessagesBeta = "messages-2023-12-15"
	// AnthropicAPIToolsBeta is the beta version of the Anthropic API that enables the tools endpoint.
	AnthropicAPIToolsBeta = "tools-2024-04-04"
)

Variables

View Source
var (
	ErrAnthropicInvalidRequest = errors.New("invalid request: there was an issue with the format or content of your request")
	ErrAnthropicUnauthorized   = errors.New("unauthorized: there's an issue with your API key")
	ErrAnthropicForbidden      = errors.New("forbidden: your API key does not have permission to use the specified resource")
	ErrAnthropicRateLimit      = errors.New("your account has hit a rate limit")
	ErrAnthropicInternalServer = errors.New("an unexpected error has occurred internal to Anthropic's systems")

	ErrAnthropicApiKeyRequired = errors.New("apiKey is required")
)

Functions

This section is empty.

Types

type Client

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

Client represents the Anthropic API client and its configuration.

func NewClient

func NewClient(apiKey string, options ...GenericOption[Client]) (*Client, error)

NewClient initializes a new Anthropic API client with the required headers.

func (*Client) Complete

func (c *Client) Complete(req *CompletionRequest) (*CompletionResponse, error)

Complete sends a completion request to the API and returns a single completion.

func (*Client) CompleteStream

func (c *Client) CompleteStream(req *CompletionRequest) (<-chan StreamResponse, <-chan error)

func (*Client) Message added in v2.1.2

func (c *Client) Message(req *MessageRequest) (*MessageResponse, error)

func (*Client) MessageStream added in v2.1.2

func (c *Client) MessageStream(req *MessageRequest) (<-chan MessageStreamResponse, <-chan error)

type CompletionEventType added in v2.1.2

type CompletionEventType string

Define a separate type for completion events

type CompletionOption

type CompletionOption func(*CompletionRequest)

type CompletionRequest

type CompletionRequest struct {
	Prompt            string   `json:"prompt"`
	Model             Model    `json:"model"`
	MaxTokensToSample int      `json:"max_tokens_to_sample"`
	StopSequences     []string `json:"stop_sequences,omitempty"` // optional
	Stream            bool     `json:"stream,omitempty"`         // optional
	Temperature       float64  `json:"temperature,omitempty"`    // optional
	TopK              int      `json:"top_k,omitempty"`          // optional
	TopP              float64  `json:"top_p,omitempty"`          // optional
}

CompletionRequest is the request to the Anthropic API for a completion.

func NewCompletionRequest

func NewCompletionRequest(prompt string, options ...GenericOption[CompletionRequest]) *CompletionRequest

NewCompletionRequest creates a new CompletionRequest with the given prompt and options.

prompt: the prompt for the completion request. options: optional GenericOptions to customize the completion request. Returns a pointer to the newly created CompletionRequest.

type CompletionResponse

type CompletionResponse struct {
	Completion string `json:"completion"`
	StopReason string `json:"stop_reason"`
	Stop       string `json:"stop"`
}

CompletionResponse is the response from the Anthropic API for a completion request.

type ContentBlock added in v2.1.9

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

ContentBlock interface to allow for both TextContentBlock and ImageContentBlock

func NewImageContentBlock added in v2.1.9

func NewImageContentBlock(mediaType MediaType, base64Data string) ContentBlock

NewImageContentBlock creates a new image content block with the given media type and base64 data.

func NewTextContentBlock added in v2.1.9

func NewTextContentBlock(text string) ContentBlock

Helper functions to create text and image content blocks easily

func NewToolResultContentBlock added in v2.2.3

func NewToolResultContentBlock(toolUseID string, content interface{}, isError bool) ContentBlock

NewToolResultContentBlock creates a new tool result content block with the given parameters.

type ContentBlockDeltaEvent added in v2.1.5

type ContentBlockDeltaEvent struct {
	MessageEvent
	Index int `json:"index"`
	Delta struct {
		Type string `json:"type"`
		Text string `json:"text"`
	} `json:"delta"`
}

type ContentBlockStartEvent added in v2.1.5

type ContentBlockStartEvent struct {
	MessageEvent
	Index        int `json:"index"`
	ContentBlock struct {
		Type string `json:"type"`
		Text string `json:"text"`
	} `json:"content_block"`
}

type ContentBlockStopEvent added in v2.1.5

type ContentBlockStopEvent struct {
	MessageEvent
	Index int `json:"index"`
}

type GenericOption added in v2.1.3

type GenericOption[T any] func(*T)

func WithHTTPClient added in v2.2.5

func WithHTTPClient[T any](httpClient *http.Client) GenericOption[T]

WithHTTPClient sets a custom HTTP client for the Client.

func WithMaxTokens

func WithMaxTokens[T any](maxTokens int) GenericOption[T]

func WithMessages added in v2.1.3

func WithMessages[T MessageRequest](messages []MessagePartRequest) GenericOption[T]

func WithMetadata added in v2.1.3

func WithMetadata[T MessageRequest](metadata interface{}) GenericOption[T]

func WithModel

func WithModel[T any](model Model) GenericOption[T]

func WithStopSequences

func WithStopSequences[T any](stopSequences []string) GenericOption[T]

func WithStream added in v2.1.3

func WithStream[T any](stream bool) GenericOption[T]

func WithStreaming

func WithStreaming[T any](stream bool) GenericOption[T]

func WithSystemPrompt added in v2.1.3

func WithSystemPrompt[T MessageRequest](systemPrompt string) GenericOption[T]

func WithTemperature

func WithTemperature[T any](temperature float64) GenericOption[T]

func WithToolChoice added in v2.2.2

func WithToolChoice[T MessageRequest](toolType, toolName string) GenericOption[T]

func WithTopK

func WithTopK[T any](topK int) GenericOption[T]

func WithTopP

func WithTopP[T any](topP float64) GenericOption[T]

type ImageContentBlock added in v2.1.9

type ImageContentBlock struct {
	Type   string      `json:"type"`
	Source ImageSource `json:"source"`
}

ImageContentBlock represents a block of image content.

type ImageSource added in v2.1.9

type ImageSource struct {
	Type      string    `json:"type"`
	MediaType MediaType `json:"media_type"`
	Data      string    `json:"data"`
}

ImageSource represents the source of an image, supporting base64 encoding for now.

type InputSchema added in v2.2.0

type InputSchema struct {
	Type       string              `json:"type"`
	Properties map[string]Property `json:"properties"`
	Required   []string            `json:"required"`
}

type MediaType added in v2.1.9

type MediaType string
const (
	MediaTypeJPEG MediaType = "image/jpeg"
	MediaTypePNG  MediaType = "image/png"
	MediaTypeGIF  MediaType = "image/gif"
	MediaTypeWEBP MediaType = "image/webp"
)

type MessageDeltaEvent added in v2.1.5

type MessageDeltaEvent struct {
	MessageEvent
	Delta struct {
		StopReason   string `json:"stop_reason"`
		StopSequence string `json:"stop_sequence"`
	} `json:"delta"`
	Usage struct {
		OutputTokens int `json:"output_tokens"`
	} `json:"usage"`
}

type MessageErrorEvent added in v2.1.5

type MessageErrorEvent struct {
	MessageEvent
	Error struct {
		Type    string `json:"type"`
		Message string `json:"message"`
	} `json:"error"`
}

type MessageEvent added in v2.1.5

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

type MessageEventType added in v2.1.2

type MessageEventType string

Common types for different events

type MessageOption added in v2.1.3

type MessageOption func(*MessageRequest)

type MessagePartRequest added in v2.1.2

type MessagePartRequest struct {
	Role    string         `json:"role"`
	Content []ContentBlock `json:"content"`
}

MessagePartRequest is updated to support both text and image content blocks.

type MessagePartResponse added in v2.1.2

type MessagePartResponse struct {
	Type string `json:"type"`
	Text string `json:"text"`

	// Optional fields, only present for tools responses
	ID    string                 `json:"id,omitempty"`
	Name  string                 `json:"name,omitempty"`
	Input map[string]interface{} `json:"input,omitempty"`
}

MessageResponse is a subset of the response from the Anthropic API for a message response.

type MessageRequest added in v2.1.2

type MessageRequest struct {
	Model             Model                `json:"model"`
	Tools             []Tool               `json:"tools,omitempty"`
	Messages          []MessagePartRequest `json:"messages"`
	MaxTokensToSample int                  `json:"max_tokens"`
	SystemPrompt      string               `json:"system,omitempty"`         // optional
	Metadata          interface{}          `json:"metadata,omitempty"`       // optional
	StopSequences     []string             `json:"stop_sequences,omitempty"` // optional
	Stream            bool                 `json:"stream,omitempty"`         // optional
	Temperature       float64              `json:"temperature,omitempty"`    // optional
	ToolChoice        *ToolChoice          `json:"tool_choice,omitempty"`    // optional
	TopK              int                  `json:"top_k,omitempty"`          // optional
	TopP              float64              `json:"top_p,omitempty"`          // optional
}

MessageRequest is the request to the Anthropic API for a message request.

func NewMessageRequest added in v2.1.3

func NewMessageRequest(messages []MessagePartRequest, options ...GenericOption[MessageRequest]) *MessageRequest

NewMessageRequest creates a new MessageRequest with the provided messages and options. It takes in a slice of MessagePartRequests and optional GenericOptions and returns a pointer to a MessageRequest.

func (*MessageRequest) ContainsImageContent added in v2.1.9

func (m *MessageRequest) ContainsImageContent() bool

ContainsImageContent checks if the MessageRequest contains any ImageContentBlock.

No parameters. Returns a boolean value.

func (*MessageRequest) CountImageContent added in v2.1.9

func (m *MessageRequest) CountImageContent() int

CountImageContent counts the number of ImageContentBlock in the MessageRequest.

No parameters. Returns an integer representing the count.

type MessageResponse added in v2.1.2

type MessageResponse struct {
	ID           string                `json:"id"`
	Type         string                `json:"type"`
	Model        string                `json:"model"`
	Role         string                `json:"role"`
	Content      []MessagePartResponse `json:"content"`
	StopReason   string                `json:"stop_reason"`
	Stop         string                `json:"stop"`
	StopSequence string                `json:"stop_sequence"`
	Usage        MessageUsage          `json:"usage"`
}

MessageResponse is the response from the Anthropic API for a message response.

type MessageStartEvent added in v2.1.5

type MessageStartEvent struct {
	MessageEvent
	Message struct {
		ID           string        `json:"id"`
		Type         string        `json:"type"`
		Role         string        `json:"role"`
		Content      []interface{} `json:"content"`
		Model        string        `json:"model"`
		StopReason   string        `json:"stop_reason"`
		StopSequence string        `json:"stop_sequence"`
		Usage        struct {
			InputTokens  int `json:"input_tokens"`
			OutputTokens int `json:"output_tokens"`
		} `json:"usage"`
	} `json:"message"`
}

type MessageStopEvent added in v2.1.5

type MessageStopEvent struct {
	MessageEvent
}

type MessageStreamDelta added in v2.1.5

type MessageStreamDelta struct {
	Type         string `json:"type"`
	Text         string `json:"text"`
	StopReason   string `json:"stop_reason"`
	StopSequence string `json:"stop_sequence"`
}

type MessageStreamResponse added in v2.1.5

type MessageStreamResponse struct {
	Type  string             `json:"type"`
	Delta MessageStreamDelta `json:"delta"`
	Usage MessageStreamUsage `json:"usage"`
}

type MessageStreamUsage added in v2.1.5

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

type MessageUsage added in v2.1.5

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

type Model

type Model string

Model represents a Claude model.

const (
	// Highest level of intelligence and capability
	Claude35Sonnet Model = "claude-3-5-sonnet-20240620"

	// Most powerful model for highly complex tasks.
	Claude3Opus Model = "claude-3-opus-20240229"

	// Ideal balance of intelligence and speed for enterprise workloads
	Claude3Sonnet Model = "claude-3-sonnet-20240229"

	// Fastest and most compact model for near-instant responsiveness
	Claude3Haiku Model = "claude-3-haiku-20240307"

	// Updated version of Claude 2 with improved accuracy
	ClaudeV2_1 Model = "claude-2.1"

	// Superior performance on tasks that require complex reasoning.
	ClaudeV2 Model = "claude-2"

	// Our largest model, ideal for a wide range of more complex tasks.
	ClaudeV1 Model = "claude-v1"

	// An enhanced version of ClaudeV1 with a 100,000 token context window.
	ClaudeV1_100k Model = "claude-v1-100k"

	// A smaller model with far lower latency, sampling at roughly 40 words/sec!
	ClaudeInstantV1 Model = "claude-instant-v1"

	// An enhanced version of ClaudeInstantV1 with a 100,000 token context window.
	ClaudeInstantV1_100k Model = "claude-instant-v1-100k"

	// More robust against red-team inputs, better at precise instruction-following,
	// better at code, and better and non-English dialogue and writing.
	ClaudeV1_3 Model = "claude-v1.3"

	// An enhanced version of ClaudeV1_3 with a 100,000 token context window.
	ClaudeV1_3_100k Model = "claude-v1.3-100k"

	// An improved version of ClaudeV1, slightly improved at general helpfulness,
	// instruction following, coding, and other tasks. It is also considerably
	// better with non-English languages.
	ClaudeV1_2 Model = "claude-v1.2"

	// An earlier version of ClaudeV1.
	ClaudeV1_0 Model = "claude-v1.0"

	// Latest version of ClaudeInstantV1. It is better at a wide variety of tasks
	// including writing, coding, and instruction following. It performs better on
	// academic benchmarks, including math, reading comprehension, and coding tests.
	ClaudeInstantV1_1 Model = "claude-instant-v1.1"

	// An enhanced version of ClaudeInstantV1_1 with a 100,000 token context window.
	ClaudeInstantV1_1_100k Model = "claude-instant-v1.1-100k"

	// An earlier version of ClaudeInstantV1.
	ClaudeInstantV1_0 Model = "claude-instant-v1.0"
)

https://docs.anthropic.com/claude/docs/models-overview

func (Model) IsCompleteCompatible added in v2.1.5

func (m Model) IsCompleteCompatible() bool

func (Model) IsImageCompatible added in v2.1.9

func (m Model) IsImageCompatible() bool

func (Model) IsMessageCompatible added in v2.1.5

func (m Model) IsMessageCompatible() bool

type PingEvent

type PingEvent struct {
	MessageEvent
}

type Property added in v2.2.0

type Property struct {
	Type        string   `json:"type"`
	Enum        []string `json:"enum,omitempty"`
	Description string   `json:"description"`
}

type StreamResponse

type StreamResponse struct {
	Completion string `json:"completion"`
	StopReason string `json:"stop_reason"`
	Model      string `json:"model"`
	Stop       string `json:"stop"`
	LogID      string `json:"log_id"`
}

StreamResponse is the response from the Anthropic API for a stream of completions.

type TextContentBlock added in v2.1.9

type TextContentBlock struct {
	Type string `json:"type"`
	Text string `json:"text"`
}

TextContentBlock represents a block of text content.

type Tool added in v2.2.0

type Tool struct {
	Name        string      `json:"name"`
	Description string      `json:"description"`
	InputSchema InputSchema `json:"input_schema"`
}

type ToolChoice added in v2.2.2

type ToolChoice struct {
	Type string `json:"type"` // Type of tool choice: "tool", "any", or "auto".
	Name string `json:"name"` // Name of the tool to be used (if type is "tool").
}

ToolChoice specifies the tool preferences for a message request.

type ToolResultContentBlock added in v2.2.3

type ToolResultContentBlock struct {
	Type      string      `json:"type"`
	ToolUseID string      `json:"tool_use_id"`
	Content   interface{} `json:"content"`
	IsError   bool        `json:"is_error,omitempty"`
}

ToolResultContentBlock represents a block of tool result content.

type UnsupportedEventType added in v2.1.5

type UnsupportedEventType struct {
	Msg  string
	Code int
}

func (UnsupportedEventType) Error added in v2.1.5

func (e UnsupportedEventType) Error() string

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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