anthropic

package module
v1.0.0 Latest Latest
Warning

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

Go to latest
Published: Aug 11, 2024 License: MIT Imports: 9 Imported by: 1

README

Go Anthropic SDK

Go Reference Go Report Card

This library provides unofficial Go clients for Anthropic API.

It is heavily inspired by the Unofficial Go SDK for OpenAI API by @sashabaranov

Installation

go get github.com/adamchol/go-anthropic-sdk 

Usage

Basic Messages API example with Claude 3.5 Sonnet
package main

import (
	"context"
	"fmt"

	anthropic "github.com/adamchol/go-anthropic-sdk"
)

func main() {
	client := anthropic.NewClient("your-token")

	resp, err := client.CreateMessage(context.Background(), anthropic.MessageRequest{
		Model: anthropic.Claude35SonnetModel,
		Messages: []anthropic.InputMessage{
			{
				Role:    anthropic.MessageRoleUser,
				Content: "Hello, how are you?",
			},
		},
		MaxTokens: 4096,
	})
	if err != nil {
		fmt.Println(err)
	}

	fmt.Println(resp.Content[0].Text)
}
Other examples
Claude 3.5 Sonnet with image and text input
package main

import (
	"context"
	"encoding/base64"
	"fmt"
	"log"
	"os"

	"github.com/adamchol/go-anthropic-sdk"
)

func main() {
	client := anthropic.NewClient("your-token")

	imageBytes, err := os.ReadFile("ant.jpg")
	if err != nil {
		log.Fatalf("Failed to read image file: %v", err)
	}

	imgData := base64.StdEncoding.EncodeToString(imageBytes) // Encoding the image into base64

	resp, err := client.CreateMessage(context.Background(), anthropic.MessageRequest{
		Model: anthropic.Claude35SonnetModel,
		Messages: []anthropic.InputMessage{
			{
				Role: "user",
				ContentBlocks: []anthropic.ContentBlock{ // Using ContentBlocks field instead of Content for multiple input
					{
						Type: "text",
						Text: "Is there a living organism on this image?",
					},
					{
						Type: "image",
						Source: anthropic.ImageSource{
							Type:      anthropic.ImageSourceType, // "base64"
							MediaType: anthropic.ImageJPEGMediaType, // "image/jpeg"
							Data:      imgData,
						},
					},
				},
			},
		},
		MaxTokens: 1000,
	})
	if err != nil {
		fmt.Println(err)
	}

	fmt.Println(resp.Content[0].Text)
}
Streaming messages
package main

import (
	"context"
	"encoding/base64"
	"fmt"
	"log"
	"os"

	"github.com/adamchol/go-anthropic-sdk"
)

func main() {
	client := anthropic.NewClient("your-token")

	stream, err := client.CreateMessageStream(context.Background(), anthropic.MessageRequest{
		Model:     anthropic.Claude35SonnetModel,
		MaxTokens: 1000,
		Messages: []anthropic.InputMessage{
			{
				Role:    anthropic.MessageRoleUser,
				Content: "Hello, how are you doing today?",
			},
		},
	})

	if err != nil {
		fmt.Println(err)
		return
	}

	defer stream.Close()

	for {
		delta, err := stream.Recv()

		if err == io.EOF {
			fmt.Println()
			fmt.Println("Done")
			return
		}

		if err != nil {
			fmt.Printf("Stream error: %s", err)
			return
		}

		fmt.Print(delta.Text)
	}
}

Documentation

Index

Constants

View Source
const (
	MessageRoleAssistant = "assistant"
	MessageRoleUser      = "user"
)
View Source
const (
	TextContentObjectType       = "text"
	ImageContentObjectType      = "image"
	ToolUseContentObjectType    = "tool_use"
	ToolResultContentObjectType = "tool_result"
)
View Source
const (
	ImageJPEGMediaType = "image/jpeg"
	ImagePNGMediaType  = "image/png"
	ImageGIFMediaType  = "image/gif"
	ImageWebPMediaType = "image/webp"
)
View Source
const (
	Claude35SonnetModel = "claude-3-5-sonnet-20240620"
	Claude3OpusModel    = "claude-3-opus-20240229"
	Claude3SonnetModel  = "claude-3-sonnet-20240229"
	Claude3HaikuModel   = "claude-3-haiku-20240307"
)
View Source
const (
	AutoToolChoiceType = "auto"
	AnyToolChoiceType  = "any"
	ToolToolChoiceType = "tool"
)
View Source
const ImageSourceType = "base64"
View Source
const ObjectToolInputSchemaType = "object"

Variables

View Source
var (
	ErrContentFieldsMisused             = errors.New("can't use both Content and ContentBlocks properties simultaneously")
	ErrChatCompletionStreamNotSupported = errors.New("streaming is not supported with this method, please use CreateMessageStream") //nolint:lll
	ErrModelNotAvailable                = errors.New("this model is not available for Anthropic Messages API")
)

Functions

This section is empty.

Types

type APIError

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

type APIVersion

type APIVersion string

type Client

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

Anthropic API Client for making requests

func NewClient

func NewClient(apiKey string) *Client

NewClient creates an Anthropic API client with API key

func NewClientWithConfig

func NewClientWithConfig(config ClientConfig) *Client

NewClientWithConfig creates an Anthropic API client with specified configuration

func (*Client) CreateMessage

func (c *Client) CreateMessage(ctx context.Context, request MessageRequest) (response MessageResponse, err error)

CreateMessage - API call to Anthropic Messages API to create a message completion

func (*Client) CreateMessageStream added in v1.0.0

func (c *Client) CreateMessageStream(ctx context.Context, request MessageRequest) (stream *MessageStream, err error)

CreateMessageStream — API call to create a message w/ streaming support. It sets whether to stream back partial progress. If set, tokens will be sent as server-sent events as they become available, with the stream terminated by the last event of type "message_stop"

See Recv() and RecvAll() methods of MessageStream for more details of how to receive data from stream.

type ClientConfig

type ClientConfig struct {
	BaseUrl    string
	APIVersion APIVersion

	HTTPClient *http.Client
	// contains filtered or unexported fields
}

ClientConfig is a configuration of client

func DefaultConfig

func DefaultConfig(apiKey string) ClientConfig

DefaultConfig creates a standard configuration with api key. This method is called when creating new client with NewClient

type ContentBlock

type ContentBlock struct {
	Type string `json:"type"`

	// For Text type
	Text string `json:"text,omitempty"`

	// For Image type
	Source ImageSource `json:"source,omitempty"`

	// For Tool Use type
	ID    string                 `json:"id,omitempty"`
	Name  string                 `json:"name,omitempty"`
	Input map[string]interface{} `json:"input,omitempty"`

	// For Tool Result type
	ToolUseId         string            `json:"tool_use_id,omitempty"`
	IsError           bool              `json:"is_error,omitempty"`
	ToolResultContent ToolResultContent `json:"content,omitempty"`
}

ContentBlock is used to provide the InputMessage with multiple input or input other than a simple string

func (ContentBlock) MarshalJSON

func (cb ContentBlock) MarshalJSON() ([]byte, error)

type ErrorResponse

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

type ImageSource

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

type InputMessage

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

InputMessage stores content of message request. When creating new message with Client.CreateMessage, Role field is always equal to "user". Content field is used to pass just one string of content. ContentBlocks are used to pass multiple input content and/or content other than a string, like an image.

Note that Content and ContentBlocks fields cannot be used simultaneously in one InputMessage.

func (InputMessage) MarshalJSON

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

func (*InputMessage) UnmarshalJSON

func (m *InputMessage) UnmarshalJSON(bs []byte) error

type MessageRequest

type MessageRequest struct {
	Model     string         `json:"model"`
	Messages  []InputMessage `json:"messages"`
	MaxTokens int            `json:"max_tokens"`

	Temperature   int                     `json:"temperature,omitempty"`
	StopSequences []string                `json:"stop_sequences,omitempty"`
	Metadata      *MessageRequestMetadata `json:"metadata,omitempty"`
	Stream        bool                    `json:"stream,omitempty"`
	System        string                  `json:"system,omitempty"`
	TopK          int                     `json:"top_k,omitempty"`
	TopP          int                     `json:"top_p,omitempty"`

	Tools      []Tool      `json:"tools,omitempty"`
	ToolChoice *ToolChoice `json:"tool_choice,omitempty"`
}

MessageRequest represents a request structure for Anthropic Messages API

type MessageRequestMetadata

type MessageRequestMetadata struct {
	UserId string `json:"user_id,omitempty"`
}

type MessageResponse

type MessageResponse struct {
	ID           string         `json:"id"`
	Type         string         `json:"type"`
	Content      []ContentBlock `json:"content"`
	Role         string         `json:"role"`
	Model        string         `json:"model"`
	StopReason   StopReason     `json:"stop_reason"`
	StopSequence string         `json:"stop_sequence,omitempty"`
	Usage        Usage          `json:"usage"`
}

type MessageStream added in v1.0.0

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

func (MessageStream) Close added in v1.0.0

func (stream MessageStream) Close() error

func (MessageStream) Recv added in v1.0.0

func (stream MessageStream) Recv() (MessageStreamDelta, error)

Recv is the same as RecvAll() but receives only events with the type "content_block_delta", which carry the content of the response, and returns them as MessageStreamDelta

func (MessageStream) RecvAll added in v1.0.0

func (stream MessageStream) RecvAll() (response MessageStreamEvent, err error)

RecvAll receives all types of events from Anthropic Messages API and returns them as MessageStreamEvent If you want to process all events, check the type of event first to know what fields are available.

type MessageStreamDelta added in v1.0.0

type MessageStreamDelta struct {
	Type string `json:"type"`

	Text string `json:"text,omitempty"`

	PartialJSON string `json:"partial_json,omitempty"`
}

type MessageStreamError added in v1.0.0

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

type MessageStreamEvent added in v1.0.0

type MessageStreamEvent struct {
	Type  MessageStreamEventType `json:"type"`
	Index int                    `json:"index,omitempty"`

	// For message_start type
	Message MessageResponse `json:"message,omitempty"`

	// For content_block_start type
	ContentBlock ContentBlock `json:"content_block,omitempty"`

	// For content_block_delta type
	Delta MessageStreamDelta `json:"delta,omitempty"`

	// For error type
	Error MessageStreamError `json:"error,omitempty"`
}

type MessageStreamEventType added in v1.0.0

type MessageStreamEventType string
const (
	MessageStartStreamEventType      MessageStreamEventType = "message_start"
	ContentBlockStartStreamEventType MessageStreamEventType = "content_block_start"
	PingStreamEventType              MessageStreamEventType = "ping"
	ContentBlockDeltaStreamEventType MessageStreamEventType = "content_block_delta"
	MessageDeltaStreamEventType      MessageStreamEventType = "message_delta"
	MessageStopStreamEventType       MessageStreamEventType = "message_stop"
	ContentBlockStopStreamEventType  MessageStreamEventType = "content_block_stop"
	ErrStreamEventType               MessageStreamEventType = "error"
)

type StopReason

type StopReason string
const (
	StopReasonEndTurn      StopReason = "end_turn"
	StopReasonMaxTokens    StopReason = "max_tokens"
	StopReasonStopSequence StopReason = "stop_sequence"
	StopReasonToolUser     StopReason = "tool_use"
)

type Tool

type Tool struct {
	Name        string                 `json:"name"`
	Description string                 `json:"description,omitempty"`
	InputSchema map[string]interface{} `json:"input_schema"`
}

type ToolChoice

type ToolChoice struct {
	Type string `json:"type"`
	Name string `json:"name,omitempty"`
}

type ToolInputSchema

type ToolInputSchema struct {
	Type       string                 `json:"type"`
	Properties map[string]interface{} `json:"properties,omitempty"`
}

type ToolResultContent

type ToolResultContent struct {
	Type string `json:"type"`

	// For Text type
	Text string `json:"text,omitempty"`

	// For Image type
	Source ImageSource `json:"source,omitempty"`
}

func (ToolResultContent) MarshalJSON

func (trs ToolResultContent) MarshalJSON() ([]byte, error)

type Usage

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

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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