go_anthropic_api

package module
v0.0.0-...-3926012 Latest Latest
Warning

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

Go to latest
Published: Apr 3, 2024 License: MIT Imports: 11 Imported by: 0

README

go-anthropic-ai

This is a Golang library for interacting with Anthropic's Claude AI API. It provides a simple and easy-to-use interface for sending requests to the API and receiving responses.

Installation

To install the library, use the following command:

go get github.com/NikitosnikN/go-anthropic-api

Usage

Here are some examples how to use library:

Basic text request
package main

import (
	"fmt"
	"context"
	claude "github.com/NikitosnikN/go-anthropic-api"
)

func main() {
	// Create a new Claude client
	client := claude.NewClient("your-api-key")

	// Create a message request instance
	message := claude.MessagesRequest{
		Model:     "claude-3-haiku-20240307",
		MaxTokens: 1024,
	}
	message.AddTextMessage("user", "hello world")

	// Send request 
	response, _ := client.CreateMessageRequest(context.Background(), message)

	// Print the response
	fmt.Println(response)
}
Streaming response without accumulating response text
package main

import (
	"context"
	"fmt"
	claude "github.com/NikitosnikN/go-anthropic-api"
	"io"
)

func main() {
	// Create a new Claude client
	client := claude.NewClient("your-api-key")

	// Create a message request instance
	message := claude.MessagesRequest{
		Model:     "claude-3-haiku-20240307",
		MaxTokens: 1024,
	}
	message.AddTextMessage("user", "hello world")

	// Send request 
	stream, err := client.CreateMessageRequestStream(context.Background(), message)

	if err != nil {
		panic(err)
	}

	// Read response
	for {
		part, err := stream.ReadMessage(false)

		if err == io.EOF {
			break
		}
		if err != nil {
			panic(err)
		}
		fmt.Println(part)
		// Hello
		// !
		// 	How
		//  can
		//  I
		//  assist
		//  you
		//  today
		// ?
	}
}
Streaming response with response text accumulation
package main

import (
	"context"
	"fmt"
	claude "github.com/NikitosnikN/go-anthropic-api"
	"io"
)

func main() {
	// Create a new Claude client
	client := claude.NewClient("your-api-key")

	// Create a message request instance
	message := claude.MessagesRequest{
		Model:     "claude-3-haiku-20240307",
		MaxTokens: 1024,
	}
	message.AddTextMessage("user", "hello world")

	// Send request 
	stream, err := client.CreateMessageRequestStream(context.Background(), message)

	if err != nil {
		panic(err)
	}

	// Read response
	for {
		part, err := stream.ReadMessage(true)

		if err == io.EOF {
			break
		}
		if err != nil {
			panic(err)
		}
		fmt.Println(part)
		// Hello
		// Hello!
		// Hello! How
		// Hello! How can
		// Hello! How can I
		// Hello! How can I assist
		// Hello! How can I assist you
		// Hello! How can I assist you today
		// Hello! How can I assist you today?
	}
}
Sending image with caption
package main

import (
	"context"
	"fmt"
	claude "github.com/NikitosnikN/go-anthropic-api"
	"io"
	"os"
)

func main() {
	// Create a new Claude client
	client := claude.NewClient("your-api-key")

	// Read image file
	file, err := os.Open("giraffe.jpg")
	if err != nil {
		panic(err)
	}
	defer file.Close()
	content, err := io.ReadAll(file)
	if err != nil {
		panic(err)
	}

	// Create a message request instance
	message := claude.MessagesRequest{
		Model:     "claude-3-haiku-20240307",
		MaxTokens: 1024,
	}

	message.AddImageMessage("user", content, "image/jpeg", "who is it?")

	// Send request 
	response, _ := client.CreateMessageRequest(context.Background(), message)

	// Print the response
	fmt.Println(response)
}

Features

  • Simple and intuitive API
  • Supports sending requests and receiving responses
  • Handles authentication with API keys
  • Provides error handling and logging
  • Well-documented code and examples

Roadmap

Here are some planned features and improvements for future releases:

  • Add support for Messages API
  • Add support for Messages API streaming responses
  • Add image support for Messages API
  • Implement rate limiting and retry mechanisms
  • Provide more configuration options for the client
  • Improve error handling and logging
  • Add unit tests and integration tests
  • Create a CLI tool for interacting with the API

Contributing

Contributions are welcome! If you find any issues or have suggestions for improvements, please open an issue or submit a pull request.

License

This library is licensed under the MIT License.

Contact

If you have any questions or feedback, please contact the maintainer at me@nikitayugov.com

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type APIError

type APIError struct {
	Type         string          `json:"type"`
	ErrorDetails APIErrorDetails `json:"error"`
}

func (*APIError) Error

func (e *APIError) Error() string

type APIErrorDetails

type APIErrorDetails struct {
	Type    string
	Message string
}

type Client

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

func NewClient

func NewClient(apiKey string) *Client

func (*Client) CreateMessageRequest

func (c *Client) CreateMessageRequest(ctx context.Context, request MessagesRequest) (*MessageResponse, error)

CreateMessageRequest - API call to create message

func (*Client) CreateMessageRequestStream

func (c *Client) CreateMessageRequestStream(ctx context.Context, request MessagesRequest) (*StreamReader, error)

func (*Client) SetApiUrl

func (c *Client) SetApiUrl(apiUrl string)

func (*Client) SetApiVersion

func (c *Client) SetApiVersion(apiVersion string)

func (*Client) SetProxy

func (c *Client) SetProxy(proxyUrl string) error

type Message

type Message struct {
	Role    string            `json:"role"`
	Content []*MessageContent `json:"content"`
}

type MessageContent

type MessageContent struct {
	Type   string              `json:"type"`
	Text   string              `json:"text,omitempty"`
	Source *MessageContentType `json:"source,omitempty"`
}

type MessageContentType

type MessageContentType struct {
	Type      string `json:"type,omitempty"`
	MediaType string `json:"media_type,omitempty"`
	Data      string `json:"data,omitempty"`
}

type MessageMetadata

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

type MessageResponse

type MessageResponse struct {
	Id            string                `json:"id"`
	Type          string                `json:"type"`
	Role          string                `json:"role"`
	Model         string                `json:"model"`
	Content       []*MessageContent     `json:"content"`
	StopReason    string                `json:"stop_reason"`
	StopSequences string                `json:"stop_sequences"`
	Usage         *MessageResponseUsage `json:"usage"`
}

type MessageResponseUsage

type MessageResponseUsage struct {
	InputToken  int32 `json:"input_token"`
	OutputToken int32 `json:"output_token"`
}

type MessageRole

type MessageRole string
const (
	User      MessageRole = "user"
	Assistant MessageRole = "assistant"
)

type MessagesRequest

type MessagesRequest struct {
	Model         string           `json:"model"`
	Messages      []*Message       `json:"messages"`
	System        string           `json:"system,omitempty"`
	MaxTokens     int              `json:"max_tokens"`
	Metadata      *MessageMetadata `json:"metadata,omitempty"`
	StopSequences []string         `json:"stop_sequences,omitempty"`
	Stream        bool             `json:"stream,omitempty"`
	Temperature   float32          `json:"temperature,omitempty"`
	TopP          float32          `json:"top_p,omitempty"`
	TopK          int32            `json:"top_k,omitempty"`
}

func NewMessageRequest

func NewMessageRequest(model string, maxTokens int) *MessagesRequest

func (*MessagesRequest) AddImageMessage

func (m *MessagesRequest) AddImageMessage(role MessageRole, image []byte, imageMediaType string, caption string)

func (*MessagesRequest) AddSystemMessage

func (m *MessagesRequest) AddSystemMessage(text string)

func (*MessagesRequest) AddTextMessage

func (m *MessagesRequest) AddTextMessage(role MessageRole, text string)

func (*MessagesRequest) ClearMessages

func (m *MessagesRequest) ClearMessages()

type StreamReader

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

func NewStreamReader

func NewStreamReader(reader io.Reader) *StreamReader

func (*StreamReader) ReadMessage

func (s *StreamReader) ReadMessage(accumulateResponse bool) (string, error)

ReadMessage reads a single line from the stream. Skips any lines that do not start with "data:" When it receives message with type content_block_stop, it stops reading the stream.

Jump to

Keyboard shortcuts

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