anthropic

package module
v1.0.0 Latest Latest
Warning

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

Go to latest
Published: Nov 26, 2023 License: Apache-2.0 Imports: 10 Imported by: 0

README

Go Anthropic

Go Reference

This library provides unofficial Go clients for Anthropic API. We support:

  • Complete

Installation

go get github.com/anhao/go-anthropic

Currently, go-anthropic requires Go version 1.18 or greater.

Usage

Anthropic example usage:
package main

import (
	"context"
	"fmt"
	anthropic "github.com/anhao/go-anthropic"
)

func main() {
	client := anthropic.NewClient("your token")
	resp, err := client.CreateComplete(
		context.Background(),
		anthropic.CompleteRequest{
			Model: anthropic.ClaudeV2Dot1,
			Prompt: anthropic.GetPromptFromString("Hello"),
			MaxTokensToSample: 400,
		},
	)

	if err != nil {
		fmt.Printf("Complete error: %v\n", err)
		return
	}

	fmt.Println(resp.Completion)
}

Getting an Anthropic API Key:
  1. Visit the OpenAI website at https://console.anthropic.com/account/keys.
  2. If you don't have an account, click on "Sign Up" to create one. If you do, click "Log In".
  3. Once logged in, navigate to your API key management page.
  4. Click on "Create Key".
  5. Enter a name for your new key, then click "Create secret key".
  6. Your new API key will be displayed. Use this key to interact with the Anthropic API.

Note: Your API key is sensitive information. Do not share it with anyone.

Other examples:
Completion streaming
package main

import (
	"context"
	"errors"
	"fmt"
	"io"
	anthropic "github.com/anhao/go-anthropic"
)

func main() {
	c := anthropic.NewClient("your token")
	ctx := context.Background()

	req := anthropic.CompleteRequest{
		Model:     anthropic.ClaudeV2,
		Stream: true,
		MaxTokensToSample: 400,
		Prompt: anthropic.GetPromptFromString("Hello"),
	}
	stream, err := c.CreateCompleteStream(ctx, req)
	if err != nil {
		fmt.Printf("ChatCompletionStream error: %v\n", err)
		return
	}
	defer stream.Close()

	fmt.Printf("Stream response: ")
	for {
		response, err := stream.Recv()
		if errors.Is(err, io.EOF) {
			fmt.Println("\nStream finished")
			return
		}

		if err != nil {
			fmt.Printf("\nStream error: %v\n", err)
			return
		}

		fmt.Printf(response.Completion)
	}
}

Thank you

Documentation

Index

Constants

View Source
const (
	ClaudeV2Dot1        = "claude-2.1"
	ClaudeV2            = "claude-2"
	ClaudeV2Dot0        = "claude-2.0"
	ClaudeInstantV1     = "claude-instant-v1"
	ClaudeInstantV1Dot2 = "claude-instant-1.2"
)
View Source
const (
	MessageSenderSystem    = "system"
	MessageSenderHuman     = "\n\nHuman"
	MessageSenderAssistant = "\n\nAssistant"
)

Variables

View Source
var (
	ErrCompleteStreamNotSupported        = errors.New("streaming is not supported with this method, please use CreateCompletionStream") //nolint:lll
	ErrCompletePromptNotEmpty            = errors.New("prompt is not empty")
	ErrCompleteMaxTokensToSmapleNotEmpty = errors.New("max_tokens_to_sample is not empty")
)
View Source
var (
	ErrTooManyEmptyStreamMessages = errors.New("stream has sent too many empty messages")
)

Functions

func GetPromptFromMessages

func GetPromptFromMessages(msg []*Message) string

func GetPromptFromString

func GetPromptFromString(question string) string

func GetPromptFromStringWithSystemMessage

func GetPromptFromStringWithSystemMessage(system, human string) string

Types

type APIError

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

APIError provides error information returned by the OpenAI API. InnerError struct is only valid for Azure OpenAI Service.

func (*APIError) Error

func (e *APIError) Error() string

func (*APIError) UnmarshalJSON

func (e *APIError) UnmarshalJSON(data []byte) (err error)

type Client

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

func NewClient

func NewClient(authToken string) *Client

func NewClientWithConfig

func NewClientWithConfig(config ClientConfig) *Client

func (*Client) CreateComplete

func (c *Client) CreateComplete(ctx context.Context, request CompleteRequest) (response CompleteResponse, err error)

func (*Client) CreateCompleteStream

func (c *Client) CreateCompleteStream(
	ctx context.Context,
	request CompleteRequest,
) (stream *CompletionStream, err error)

type ClientConfig

type ClientConfig struct {
	ApiKey             string
	Version            string
	HTTPClient         *http.Client
	EmptyMessagesLimit uint
	BaseURL            string
}

func DefaultConfig

func DefaultConfig(apikey string) ClientConfig

type CompleteMetaData

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

type CompleteRequest

type CompleteRequest struct {
	Model             string           `json:"model"`
	Prompt            string           `json:"prompt"`
	MaxTokensToSample int              `json:"max_tokens_to_sample"`
	StopSequences     []string         `json:"stop_sequences,omitempty"`
	Temperature       float32          `json:"temperature,omitempty"`
	TopP              float32          `json:"top_p,omitempty"`
	TopK              int              `json:"top_k,omitempty"`
	Metadata          CompleteMetaData `json:"metadata,omitempty"`
	Stream            bool             `json:"stream,omitempty"`
}

type CompleteResponse

type CompleteResponse struct {
	Completion string  `json:"completion"`
	StopReason *string `json:"stop_reason"`
	Model      string  `json:"model"`
	Stop       *string `json:"stop"`
	LogId      string  `json:"log_id"`
}

type CompletionStream

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

func (CompletionStream) Close

func (stream CompletionStream) Close()

func (CompletionStream) Recv

func (stream CompletionStream) Recv() (response T, err error)

type ErrorResponse

type ErrorResponse struct {
	Error *APIError `json:"error,omitempty"`
}

type Message

type Message struct {
	Sender  UserType // The sender's name (e.g., "Human" or a username)
	Content string   // The content of the message
}

type RequestError

type RequestError struct {
	HTTPStatusCode int
	Err            error
}

RequestError provides informations about generic request errors.

func (*RequestError) Error

func (e *RequestError) Error() string

func (*RequestError) Unwrap

func (e *RequestError) Unwrap() error

type UserType

type UserType string

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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