anthropic

package
v3.2.3 Latest Latest
Warning

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

Go to latest
Published: Nov 5, 2024 License: Apache-2.0 Imports: 5 Imported by: 2

Documentation

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"
	MessageEventTypeError             MessageEventType = "error"

	// Constants for completion event types
	CompletionEventTypeCompletion CompletionEventType = "completion"
	CompletionEventTypePing       CompletionEventType = "ping"
)

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

func GenerateInputSchema added in v3.0.1

func GenerateInputSchema(input interface{}) *jsonschema.Schema

func MapHTTPStatusCodeToError

func MapHTTPStatusCodeToError(code int) error

mapHTTPStatusCodeToError maps an HTTP status code to an error.

func ValidateCompleteRequest

func ValidateCompleteRequest(req *CompletionRequest) error

func ValidateCompleteStreamRequest

func ValidateCompleteStreamRequest(req *CompletionRequest) error

func ValidateMessageRequest

func ValidateMessageRequest(req *MessageRequest) error

func ValidateMessageStreamRequest

func ValidateMessageStreamRequest(req *MessageRequest) error

Types

type CompletionEventType

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,omitempty"`
	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

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

ContentBlock interface to allow for both TextContentBlock and ImageContentBlock

func NewImageContentBlock

func NewImageContentBlock(mediaType MediaType, base64Data string) ContentBlock

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

func NewTextContentBlock

func NewTextContentBlock(text string) ContentBlock

Helper functions to create text and image content blocks easily

func NewToolResultContentBlock

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

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

func NewToolUseContentBlock added in v3.1.0

func NewToolUseContentBlock(id string, name string, input interface{}) ContentBlock

type ContentBlockDeltaEvent

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

type ContentBlockStartEvent

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

type ContentBlockStopEvent

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

type GenericOption

type GenericOption[T any] func(*T)

func WithMaxTokens

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

func WithMessages

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

func WithMetadata

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

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

func WithStreaming

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

func WithSystemPrompt

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

func WithTemperature

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

func WithToolChoice

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

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

ImageContentBlock represents a block of image content.

type ImageSource

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 MediaType

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

type MessageDeltaEvent

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

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

type MessageEvent

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

type MessageEventType

type MessageEventType string

Common types for different events

type MessageOption

type MessageOption func(*MessageRequest)

type MessagePartRequest

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

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

type MessagePartResponse

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

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

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

func (m *MessageRequest) ContainsImageContent() bool

ContainsImageContent checks if the MessageRequest contains any ImageContentBlock.

No parameters. Returns a boolean value.

func (*MessageRequest) CountImageContent

func (m *MessageRequest) CountImageContent() int

CountImageContent counts the number of ImageContentBlock in the MessageRequest.

No parameters. Returns an integer representing the count.

type MessageResponse

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

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

type MessageStopEvent struct {
	MessageEvent
}

type MessageStreamDelta

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

type MessageStreamResponse

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

func ParseMessageEvent

func ParseMessageEvent(eventType MessageEventType, event string) (*MessageStreamResponse, error)

type MessageStreamUsage

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

type MessageUsage

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-latest"

	// New version of claude-3-5-sonnet
	Claude35Sonnet_20241022 Model = "claude-3-5-sonnet-20241022"

	// Former highest level of intelligence and capability
	Claude35Sonnet_20240620 Model = "claude-3-5-sonnet-20240620"

	// Fastest and most compact model for near-instant responsiveness
	Claude35Haiku Model = "claude-3-5-haiku-latest"

	// Fastest and most compact model for near-instant responsiveness, 20241022 model
	Claude35Haiku_20241022 Model = "claude-3-5-haiku-20241022"

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

func (m Model) IsCompleteCompatible() bool

func (Model) IsImageCompatible

func (m Model) IsImageCompatible() bool

func (Model) IsMessageCompatible

func (m Model) IsMessageCompatible() bool

type PingEvent

type PingEvent struct {
	MessageEvent
}

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

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

TextContentBlock represents a block of text content.

type Tool

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

type ToolChoice

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

ToolChoice specifies the tool preferences for a message request.

type ToolResultContentBlock

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 ToolUseContentBlock added in v3.1.0

type ToolUseContentBlock struct {
	Type  string      `json:"type"`
	ID    string      `json:"id"`
	Name  string      `json:"name"`
	Input interface{} `json:"input"`
}

ToolUseContentBlock represents a block of tool use content.

type UnsupportedEventType

type UnsupportedEventType struct {
	Msg  string
	Code int
}

func (UnsupportedEventType) Error

func (e UnsupportedEventType) Error() string

Directories

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

Jump to

Keyboard shortcuts

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