v1

package module
v1.1.6 Latest Latest
Warning

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

Go to latest
Published: May 21, 2024 License: MIT Imports: 12 Imported by: 0

README

claude-sdk-go

Go Reference Go Report Card

This is the unofficial Go SDK for the Anthropic Claude API.

It is designed with reference to the sashabaranov/go-openai.

Official Docs: https://docs.anthropic.com/claude/

Supported

  • /v1/messages
    • Text Message
    • Image Message
    • Streaming Messages

Getting Started

go get github.com/potproject/claude-sdk-go

Example

Create a Message
package main

import (
	"context"
	"fmt"
	"os"

	claude "github.com/potproject/claude-sdk-go"
)

func main() {
	apiKey := os.Getenv("API_KEY")
	c := claude.NewClient(apiKey)
	m := claude.RequestBodyMessages{
		Model:     "claude-3-opus-20240229",
		MaxTokens: 64,
		Messages: []claude.RequestBodyMessagesMessages{
			{
				Role:    claude.MessagesRoleUser,
				Content: "Hello, world!",
				// Alternatively, you can use ContentTypeText
				//
				// ContentTypeText: []claude.RequestBodyMessagesMessagesContentTypeText{
				// 	{
				// 		Text: "Hello, world!",
				// 	},
				// },
			},
		},
	}
	ctx := context.Background()
	res, err := c.CreateMessages(ctx, m)
	if err != nil {
		panic(err)
	}
	fmt.Println(res.Content[0].Text)
	// Output:
	// Hello! How can I assist you today?
}

Create a Streaming Message
Create a Streaming Message
package main

import (
	"context"
	"errors"
	"fmt"
	"io"
	"os"

	claude "github.com/potproject/claude-sdk-go"
)

func main() {
	apiKey := os.Getenv("API_KEY")
	c := claude.NewClient(apiKey)
	m := claude.RequestBodyMessages{
		Model:     "claude-3-opus-20240229",
		MaxTokens: 64,
		Messages: []claude.RequestBodyMessagesMessages{
			{
				Role:    claude.MessagesRoleUser,
				Content: "Hello, world!",
			},
		},
	}
	ctx := context.Background()
	stream, err := c.CreateMessagesStream(ctx, m)
	if err != nil {
		panic(err)
	}
	defer stream.Close()
	for {
		res, err := stream.Recv()
		if errors.Is(err, io.EOF) {
			break
		}
		if err != nil {
			panic(err)
		}
		fmt.Printf("%s", res.Content[0].Text)
	}
	fmt.Println()
	// Output:
	// Hello! How can I assist you today?
	//
}

Create a Message with Image
Create a Message with Image
package main

import (
	"context"
	"fmt"
	"os"

	claude "github.com/potproject/claude-sdk-go"
)

func main() {
	apiKey := os.Getenv("API_KEY")
	c := claude.NewClient(apiKey)
	m := claude.RequestBodyMessages{
		Model:     "claude-3-opus-20240229",
		MaxTokens: 1024,
		Messages: []claude.RequestBodyMessagesMessages{
			{
				Role: claude.MessagesRoleUser,
				ContentTypeImage: []claude.RequestBodyMessagesMessagesContentTypeImage{
					{
						Source: claude.RequestBodyMessagesMessagesContentTypeImageSource{
							Type:      "base64",
							MediaType: "image/png",
							Data:      "iVBORw0KG...",
						},
					},
				},
			},
		},
	}
	ctx := context.Background()
	res, err := c.CreateMessages(ctx, m)
	if err != nil {
		panic(err)
	}
	fmt.Println(res.Content[0].Text)
}

Create a Message with Image(Load File)
Create a Message with Image(Load File)
package main

import (
	"context"
	"fmt"
	"os"

	claude "github.com/potproject/claude-sdk-go"
)

func main() {
	apiKey := os.Getenv("API_KEY")
	c := claude.NewClient(apiKey)
	source, err := claude.TypeImageSourceLoadFile("image.png")
	if err != nil {
		panic(err)
	}
	m := claude.RequestBodyMessages{
		Model:     "claude-3-opus-20240229",
		MaxTokens: 1024,
		Messages: []claude.RequestBodyMessagesMessages{
			{
				Role: claude.MessagesRoleUser,
				ContentTypeImage: []claude.RequestBodyMessagesMessagesContentTypeImage{
					{
						Source: source,
					},
				},
			},
		},
	}
	ctx := context.Background()
	res, err := c.CreateMessages(ctx, m)
	if err != nil {
		panic(err)
	}
	fmt.Println(res.Content[0].Text)
}

LICENSE

MIT

Documentation

Overview

Example
package main

import (
	"context"
	"fmt"
	"os"

	claude "github.com/potproject/claude-sdk-go"
)

func main() {
	apiKey := os.Getenv("API_KEY")
	c := claude.NewClient(apiKey)
	m := claude.RequestBodyMessages{
		Model:     "claude-3-opus-20240229",
		MaxTokens: 64,
		Messages: []claude.RequestBodyMessagesMessages{
			{
				Role:    claude.MessagesRoleUser,
				Content: "Hello, world!",
			},
		},
	}
	ctx := context.Background()
	res, err := c.CreateMessages(ctx, m)
	if err != nil {
		panic(err)
	}
	fmt.Println(res.Content[0].Text)
}
Output:
Hello! How can I assist you today?
Example (Stream)
package main

import (
	"context"
	"errors"
	"fmt"
	"io"
	"os"

	claude "github.com/potproject/claude-sdk-go"
)

func main() {
	apiKey := os.Getenv("API_KEY")
	c := claude.NewClient(apiKey)
	m := claude.RequestBodyMessages{
		Model:     "claude-3-opus-20240229",
		MaxTokens: 64,
		Messages: []claude.RequestBodyMessagesMessages{
			{
				Role:    claude.MessagesRoleUser,
				Content: "Hello, world!",
			},
		},
	}
	ctx := context.Background()
	stream, err := c.CreateMessagesStream(ctx, m)
	if err != nil {
		panic(err)
	}
	defer stream.Close()
	for {
		res, err := stream.Recv()
		if errors.Is(err, io.EOF) {
			break
		}
		if err != nil {
			panic(err)
		}
		fmt.Printf("%s", res.Content[0].Text)
	}
	fmt.Println()
}
Output:
Hello! How can I assist you today?
Example (TypeImage)
package main

import (
	"context"
	"fmt"
	"os"

	claude "github.com/potproject/claude-sdk-go"
)

func main() {
	apiKey := os.Getenv("API_KEY")
	c := claude.NewClient(apiKey)
	m := claude.RequestBodyMessages{
		Model:     "claude-3-opus-20240229",
		MaxTokens: 1024,
		Messages: []claude.RequestBodyMessagesMessages{
			{
				Role: claude.MessagesRoleUser,
				ContentTypeImage: []claude.RequestBodyMessagesMessagesContentTypeImage{
					{
						Source: claude.RequestBodyMessagesMessagesContentTypeImageSource{
							Type:      "base64",
							MediaType: "image/png",
							Data:      "iVBORw0KGgoAAAANSUhEUgAAAQAAAAEACAIAAADTED8xAAADMElEQVR4nOzVwQnAIBQFQYXff81RUkQCOyDj1YOPnbXWPmeTRef+/3O/OyBjzh3CD95BfqICMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMO0TAAD//2Anhf4QtqobAAAAAElFTkSuQmCC",
						},
					},
				},
			},
		},
	}
	ctx := context.Background()
	res, err := c.CreateMessages(ctx, m)
	if err != nil {
		panic(err)
	}
	fmt.Println(res.Content[0].Text)
}
Output:
The image shows a smooth gradient transitioning from a bright, vibrant orange at the bottom to a light blue at the top. The colors blend seamlessly into each other, creating a visually striking and aesthetically pleasing effect. The simplicity of the gradient allows the colors to be the main focus, showcasing their luminosity and the way they interact with one another. This type of gradient is often used as a background or design element to add depth, warmth, and visual interest to various digital or print media projects.

Index

Examples

Constants

View Source
const (
	MessagesRoleUser      = "user"
	MessagesRoleAssistant = "assistant"
)
View Source
const (
	MessagesStreamResponseTypeMessageStart      = "message_start"
	MessagesStreamResponseTypeContentBlockStart = "content_block_start"
	MessagesStreamResponseTypePing              = "ping"
	MessagesStreamResponseTypeContentBlockDelta = "content_block_delta"
	MessagesStreamResponseTypeContentBlockStop  = "content_block_stop"
	MessagesStreamResponseTypeMessageDelta      = "message_delta"
	MessagesStreamResponseTypeMessageStop       = "message_stop"
	MessagesStreamResponseTypeError             = "error"
)

Constants for SSE event types

Variables

This section is empty.

Functions

This section is empty.

Types

type Client

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

func NewClient

func NewClient(apiKey string) *Client

func NewClientWithConfig

func NewClientWithConfig(config ClientConfig) *Client

func (*Client) CreateMessages

func (c *Client) CreateMessages(ctx context.Context, body RequestBodyMessages) (*ResponseBodyMessages, error)

func (*Client) CreateMessagesStream

func (c *Client) CreateMessagesStream(ctx context.Context, body RequestBodyMessages) (*CreateMessagesStream, error)

CreateMessagesStream initializes a new streaming connection for messages

func (*Client) SetVersion

func (c *Client) SetVersion(version string)

type ClientConfig

type ClientConfig struct {
	ApiKey string

	Version string
	Beta    string // Using Beta API : anthropic-beta Header

	BaseURL    string
	Endpoint   string
	HTTPClient *http.Client
}

type CreateMessagesStream

type CreateMessagesStream struct {
	Connection                 *sse.Connection
	Unsubscribe                func()
	Event                      chan sse.Event
	Error                      chan error
	ResponseBodyMessagesStream ResponseBodyMessagesStream
}

CreateMessagesStream struct holds the connection and event channels for streaming

func (*CreateMessagesStream) Close

func (c *CreateMessagesStream) Close()

Close closes the streaming connection and cleans up resources

func (*CreateMessagesStream) Recv

Recv receives events from the streaming connection and updates usage data

type RequestBodyMessages

type RequestBodyMessages struct {
	Model         string                        `json:"model"`
	Messages      []RequestBodyMessagesMessages `json:"messages"`
	System        string                        `json:"system"` // optional
	MaxTokens     int                           `json:"max_tokens"`
	MetaData      map[string]interface{}        `json:"metadata"`       // optional
	StopSequences []string                      `json:"stop_sequences"` // optional
	Stream        bool                          `json:"stream"`         // optional
	Temperature   float64                       `json:"temperature"`    // optional
	TopP          float64                       `json:"top_p"`          // optional
	TopK          float64                       `json:"top_k"`          // optional
}

type RequestBodyMessagesMessages

type RequestBodyMessagesMessages struct {
	Role       string      `json:"role"`
	Content    string      `json:"-"`
	ContentRaw interface{} `json:"content"` // This is used to store the actual content sent in the request
	// Added fields for structured content
	ContentTypeText  []RequestBodyMessagesMessagesContentTypeText  `json:"-"`
	ContentTypeImage []RequestBodyMessagesMessagesContentTypeImage `json:"-"`
}

type RequestBodyMessagesMessagesContentTypeImage

type RequestBodyMessagesMessagesContentTypeImage struct {
	Type   string                                            `json:"type"` // always "image"`
	Source RequestBodyMessagesMessagesContentTypeImageSource `json:"source"`
}

type RequestBodyMessagesMessagesContentTypeImageSource

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

type RequestBodyMessagesMessagesContentTypeText

type RequestBodyMessagesMessagesContentTypeText struct {
	Type string `json:"type"` // always "text"`
	Text string `json:"text"`
}

type ResponseBodyMessages

type ResponseBodyMessages struct {
	Id           string                        `json:"id"`
	Type         string                        `json:"type"` // always "message"
	Role         string                        `json:"role"` // always "assistant"
	Content      []ResponseBodyMessagesContent `json:"content"`
	Model        string                        `json:"model"`
	StopReason   string                        `json:"stop_reason"` // "end_turn" or "max_tokens", "stop_sequence", null
	StopSequence string                        `json:"stop_sequence"`
	Usage        struct {
		InputTokens  int64 `json:"input_tokens"`
		OutputTokens int64 `json:"output_tokens"`
	} `json:"usage"`
}

type ResponseBodyMessagesContent

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

type ResponseBodyMessagesContentStream

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

ResponseBodyMessagesContentStream struct holds the content of the streaming messages

type ResponseBodyMessagesStream

type ResponseBodyMessagesStream struct {
	Id           string                              `json:"id"`
	Type         string                              `json:"type"` // always "message"
	Role         string                              `json:"role"` // always "assistant"
	Content      []ResponseBodyMessagesContentStream `json:"content"`
	Model        string                              `json:"model"`
	StopReason   string                              `json:"stop_reason"` // "end_turn" or "max_tokens", "stop_sequence", null
	StopSequence string                              `json:"stop_sequence"`
	Usage        struct {
		InputTokens  int64 `json:"input_tokens"`
		OutputTokens int64 `json:"output_tokens"`
	} `json:"usage"`
}

ResponseBodyMessagesStream struct holds the response data for streaming messages

type ResponseContentBlockDeltaStream

type ResponseContentBlockDeltaStream struct {
	Type  string `json:"type"`
	Index int64  `json:"index"`
	Delta struct {
		Type string `json:"type"`
		Text string `json:"text"`
	} `json:"delta"`
}

ResponseContentBlockDeltaStream struct holds the content block delta event data

type ResponseContentMessageStartStream

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

ResponseContentMessageStartStream struct holds the initial message start event data

type ResponseError

type ResponseError struct {
	Error struct {
		Message string `json:"message"`
	} `json:"error"`
}

type ResponseMessageDeltaStream

type ResponseMessageDeltaStream struct {
	Type  string `json:"type"`
	Delta struct {
		StopReason   string `json:"stop_reason"`
		StopSequence string `json:"stop_sequence"`
	} `json:"delta"`
	Usage struct {
		OutputTokens int64 `json:"output_tokens"`
	} `json:"usage"`
}

ResponseMessageDeltaStream struct holds the message delta event data

Jump to

Keyboard shortcuts

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