claude

package module
v1.0.2 Latest Latest
Warning

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

Go to latest
Published: Apr 25, 2024 License: MPL-2.0 Imports: 8 Imported by: 0

README

Unofficial Anthropic SDK in Go

This project provides an unofficial Go SDK for Anthropic, a A next-generation AI assistant for your tasks, no matter the scale. The SDK makes it easy to interact with the Anthropic API in Go applications. For more information about Anthropic, including API documentation, visit the official Anthropic documentation.

GoDoc

Installation

You can install the Anthropic SDK in Go using go get:

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

Usage

To use the Anthropic SDK, you'll need to initialize a client and make requests to the Anthropic API. Here's an example of initializing a client and performing a regular and a streaming completion:

Completion Example

package main

import (
	"fmt"

	"github.com/madebywelch/anthropic-go/v2/pkg/anthropic"
	"github.com/madebywelch/anthropic-go/v2/pkg/anthropic/utils"
)

func main() {
	client, err := anthropic.NewClient("your-api-key")
	if err != nil {
		panic(err)
	}

	prompt, err := utils.GetPrompt("Why is the sky blue?")
	if err != nil {
		panic(err)
	}

	request := anthropic.NewCompletionRequest(
		prompt,
		anthropic.WithModel[anthropic.CompletionRequest](anthropic.ClaudeV2_1),
		anthropic.WithMaxTokens[anthropic.CompletionRequest](100),
	)

	// Note: Only use client.Complete when streaming is disabled, otherwise use client.CompleteStream!
	response, err := client.Complete(request)
	if err != nil {
		panic(err)
	}

	fmt.Printf("Completion: %s\n", response.Completion)
}
Completion Example Output
The sky appears blue to us due to the way the atmosphere scatters light from the sun

Completion Streaming Example

package main

import (
	"fmt"

	"github.com/madebywelch/anthropic-go/v2/pkg/anthropic"
	"github.com/madebywelch/anthropic-go/v2/pkg/anthropic/utils"
)

func main() {
	client, err := anthropic.NewClient("your-api-key")
	if err != nil {
		panic(err)
	}

	prompt, err := utils.GetPrompt("Why is the sky blue?")
	if err != nil {
		panic(err)
	}

	request := anthropic.NewCompletionRequest(
		prompt,
		anthropic.WithModel[anthropic.CompletionRequest](anthropic.ClaudeV2_1),
		anthropic.WithMaxTokens[anthropic.CompletionRequest](100),
		anthropic.WithStreaming[anthropic.CompletionRequest](true),
	)

	// Note: Only use client.CompleteStream when streaming is enabled, otherwise use client.Complete!
	resps, errs := client.CompleteStream(request)

	for {
		select {
		case resp := <-resps:
			fmt.Printf("Completion: %s\n", resp.Completion)
		case err := <-errs:
			panic(err)
		}
	}
}
Completion Streaming Example Output
There
are
a
few
reasons
why
the
sky
appears

Messages Example

package main

import (
	"fmt"

	"github.com/madebywelch/anthropic-go/v2/pkg/anthropic"
)

func main() {
	client, err := anthropic.NewClient("your-api-key")
	if err != nil {
		panic(err)
	}

	// Prepare a message request
	request := anthropic.NewMessageRequest(
		[]anthropic.MessagePartRequest{{Role: "user", Content: []anthropic.ContentBlock{anthropic.NewTextContentBlock("Hello, world!")}}},
		anthropic.WithModel[anthropic.MessageRequest](anthropic.ClaudeV2_1),
		anthropic.WithMaxTokens[anthropic.MessageRequest](20),
	)

	// Call the Message method
	response, err := client.Message(request)
	if err != nil {
		panic(err)
	}

	fmt.Println(response.Content)
}
Messages Example Output
{ID:msg_01W3bZkuMrS3h1ehqTdF84vv Type:message Model:claude-2.1 Role:assistant Content:[{Type:text Text:Hello!}] StopReason:end_turn Stop: StopSequence:}

Messages Streaming Example

package main

import (
	"fmt"
	"os"

	"github.com/madebywelch/anthropic-go/v2/pkg/anthropic"
)

func main() {
	apiKey, ok := os.LookupEnv("ANTHROPIC_API_KEY")
	if !ok {
		fmt.Printf("missing ANTHROPIC_API_KEY environment variable")
	}
	client, err := anthropic.NewClient(apiKey)
	if err != nil {
		panic(err)
	}

	// Prepare a message request
	request := anthropic.NewMessageRequest(
		[]anthropic.MessagePartRequest{{Role: "user", Content: "Hello, Good Morning!"}},
		anthropic.WithModel[anthropic.MessageRequest](anthropic.ClaudeV2_1),
		anthropic.WithMaxTokens[anthropic.MessageRequest](20),
		anthropic.WithStreaming[anthropic.MessageRequest](true),
	)

	// Call the Message method
	resps, errors := client.MessageStream(request)

	for {
		select {
		case response := <-resps:
			if response.Type == "content_block_delta" {
				fmt.Println(response.Delta.Text)
			}
			if response.Type == "message_stop" {
				fmt.Println("Message stop")
				return
			}
		case err := <-errors:
			fmt.Println(err)
			return
		}
	}
}
Messages Streaming Example Output
Good
 morning
!
 As
 an
 AI
 language
 model
,
 I
 don
't
 have
 feelings
 or
 a
 physical
 state
,
 but

Messages Tools Example

package main

import (
	"github.com/madebywelch/anthropic-go/v2/pkg/anthropic"
)

func main() {
	client, err := anthropic.NewClient("your-api-key")
	if err != nil {
		panic(err)
	}

	// Prepare a message request
	request := &anthropic.MessageRequest{
		Model:             anthropic.Claude3Opus,
		MaxTokensToSample: 1024,
		Tools: []anthropic.Tool{
			{
				Name:        "get_weather",
				Description: "Get the weather",
				InputSchema: anthropic.InputSchema{
					Type: "object",
					Properties: map[string]anthropic.Property{
						"city": {Type: "string", Description: "city to get the weather for"},
						"unit": {Type: "string", Enum: []string{"celsius", "fahrenheit"}, Description: "temperature unit to return"}},
					Required: []string{"city"},
				},
			},
		},
		Messages: []anthropic.MessagePartRequest{
			{
				Role: "user",
				Content: []anthropic.ContentBlock{
					anthropic.NewTextContentBlock("what's the weather in Charleston?"),
				},
			},
		},
	}

	// Call the Message method
	response, err := client.Message(request)
	if err != nil {
		panic(err)
	}

	if response.StopReason == "tool_use" {
		// Do something with the tool response
	}
}

Contributing

Contributions to this project are welcome. To contribute, follow these steps:

  • Fork this repository
  • Create a new branch (git checkout -b feature/my-new-feature)
  • Commit your changes (git commit -am 'Add some feature')
  • Push the branch (git push origin feature/my-new-feature)
  • Create a new pull request

License

This project is licensed under the Apache License, Version 2.0 - see the LICENSE file for details.

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, opts ...ClientOptions) (*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

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

func (*Client) MessageStream

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

type ClientOptions

type ClientOptions func(opt *clientOption)

func WithClientBaseURL

func WithClientBaseURL(baseURl string) ClientOptions

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

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

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

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
	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"`
}

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

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

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 InputSchema `json:"input_schema"`
}

type UnsupportedEventType

type UnsupportedEventType struct {
	Msg  string
	Code int
}

func (UnsupportedEventType) Error

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