anthropic

package module
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: Apr 18, 2024 License: MIT Imports: 8 Imported by: 0

README

Anthropic SDK for Go

[!NOTE]
This is not an official SDK, and I am not affiliated with Anthropic.
Official SDKs from Anthropic are available for Python, and TypeScript/JavaScript.

Client library for interacting with the Anthropic safety-first language model REST APIs.
Documentation for the REST API can be found at docs.anthropic.com.

Getting started

Requirements
Installation and usage

Import the module and run the go get command without any arguments to resolve and add the SDK to your dependencies.

import "github.com/unfunco/anthropic-sdk-go"

Construct a new REST API client with a http.Client derived from a Transport containing your Claude API key. The derived HTTP client will automatically add the API key as a header to each request sent to the API.

transport := &anthropic.Transport{APIKey: os.Getenv("ANTHROPIC_API_KEY")}
claude := anthropic.NewClient(transport.Client())

Once constructed, you can use the client to interact with the REST API.

data, _, err := claude.Messages.Create(context.Background(), &anthropic.CreateMessageInput{
    MaxTokens: 1024,
    Messages: []anthropic.Message{
        {
            Content: "Hello, Claude!",
            Role:    "user",
        },
    },
    Model: anthropic.Claude3Opus20240229,
})
Development and testing

Clone the repository and change into the anthropic-sdk-go directory.

git clone git@github.com:unfunco/anthropic-sdk-go.git
cd anthropic-sdk-go

Run the unit tests with coverage to ensure everything is working as expected.

go test -cover -v ./...

References

License

© 2024 Daniel Morris
Made available under the terms of the MIT License.

Documentation

Overview

Package anthropic provides a client library for interacting with the Anthropic safety-first language model REST APIs.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Client

type Client struct {
	Messages *MessagesService
	// contains filtered or unexported fields
}

Client manages communication with the Anthropic REST API.

func NewClient

func NewClient(httpClient *http.Client) *Client

NewClient returns a new Anthropic REST API client. If a nil httpClient is provided, a new http.Client will be used. Adapted from go-github's NewClient method: https://github.com/google/go-github/blob/master/github/github.go

func (*Client) Do

func (c *Client) Do(ctx context.Context, req *http.Request, v any) (*http.Response, error)

Do sends an API request and returns the API response. The API response is JSON decoded and stored in the value pointed to by v, or returned as an error if an API error has occurred. If v implements the io.Writer interface, the raw response body will be written to v without attempting to first decode it. If v is nil, and no error occurs, the response is returned as-is. Adapted from go-github's Client.BareDo and Client.Do methods: https://github.com/google/go-github/blob/master/github/github.go

func (*Client) NewRequest

func (c *Client) NewRequest(method, path string, body any) (*http.Request, error)

NewRequest creates an API request. A relative URL can be provided in path, in which case it is resolved relative to the BaseURL of the Client. Paths should always be specified without a preceding slash. If specified, the value pointed to by body is JSON encoded and included as the request body. Adapted from go-github's Client.NewRequest method: https://github.com/google/go-github/blob/master/github/github.go

type Content

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

type CreateMessageInput

type CreateMessageInput struct {
	// Temperature defines the amount of randomness injected into the response.
	// Note that even with a temperature of 0.0, results will not be fully
	// deterministic.
	Temperature *float64 `json:"temperature,omitempty"`
	// TopK is used to remove long tail low probability responses by only
	// sampling from the top K options for each subsequent token.
	// Recommended for advanced use cases only. You usually only need to use
	// Temperature.
	TopK *int `json:"top_k,omitempty"`
	// TopP is the nucleus-sampling parameter. Temperature or TopP should be
	// used, but not both.
	// Recommended for advanced use cases only. You usually only need to use
	// Temperature.
	TopP *float64 `json:"top_p,omitempty"`
	// Model defines the language model that will be used to complete the
	// prompt. See model.go for a list of available models.
	Model LanguageModel `json:"model"`
	// System provides a means of specifying context and instructions to the
	// model, such as specifying a particular goal or role.
	System string `json:"system,omitempty"`
	// Messages are the input messages, models are trained to operate on
	// alternating user and assistant conversational turns. When creating a new
	// message, prior conversational turns can be specified with this field,
	// and the model generates the next Message in the conversation.
	Messages []Message `json:"messages"`
	// StopSequences defines custom text sequences that will cause the model to
	// stop generating. If the model encounters any of the sequences, the
	// StopReason field will be set to "stop_sequence" and the response
	// StopSequence field will be set to the sequence that caused the model to
	// stop.
	StopSequences []string `json:"stop_sequences,omitempty"`
	// MaxTokens defines the maximum number of tokens to generate before
	// stopping. Token generation may stop before reaching this limit, this only
	// specifies the absolute maximum number of tokens to generate. Different
	// models have different maximum token limits.
	MaxTokens int `json:"max_tokens"`
}

CreateMessageInput defines a structured list of input messages.

type CreateMessageOutput

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

CreateMessageOutput defines the response from creating a new message.

func (*CreateMessageOutput) String

func (c *CreateMessageOutput) String() string

String implements the fmt.Stringer interface for CreateMessageOutput.

type LanguageModel

type LanguageModel string

LanguageModel represents a language model that can be used to complete a prompt. https://docs.anthropic.com/claude/docs/models-overview

const (
	Claude3Opus20240229   LanguageModel = "claude-3-opus-20240229"
	Claude3Sonnet20240229 LanguageModel = "claude-3-sonnet-20240229"
	Claude3Haiku20240229  LanguageModel = "claude-3-haiku-20240307"
	Claude21              LanguageModel = "claude-2.1"
	Claude20              LanguageModel = "claude-2.0"
	ClaudeInstant12       LanguageModel = "claude-instant-1.2"
)

type Message

type Message struct {
	Content string `json:"content"`
	Role    string `json:"role"`
}

type MessagesService

type MessagesService service

func (*MessagesService) Create

Create creates a new message using the provided options.

type Transport

type Transport struct {
	APIKey string
}

Transport is a http.RoundTripper that includes an API key in each request.

func (*Transport) Client

func (t *Transport) Client() *http.Client

Client returns an HTTP client that will include the API key in the request, and is safe for concurrent use by multiple goroutines.

func (*Transport) RoundTrip

func (t *Transport) RoundTrip(req *http.Request) (*http.Response, error)

RoundTrip implements the http.RoundTripper interface. It makes a copy of the HTTP request so that it complies with the requirements of the interface and adds the API key to the new request before calling the default http.RoundTripper.

type Usage

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

Usage defines billing and rate-limit usage information. Billing and rate-limiting are driven by token counts.

func (*Usage) String

func (u *Usage) String() string

String implements the fmt.Stringer interface for Usage.

Jump to

Keyboard shortcuts

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