Giter VIP home page Giter VIP logo

anthropic-go's Introduction

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.

anthropic-go's People

Contributors

kaptinlin avatar lakshmanpasala avatar madebywelch avatar molizz avatar pigeonlaser avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar

anthropic-go's Issues

Implement Stream

The OpenAI Golang SDK has a good pattern for streaming. It would be nice to see that here as well.

Support image(s) in user prompts

To implement this we need to first change Content in MessagePartRequest so that we support

  1. Array of either text and/or image content.
  2. Also implement the API limits like:
    • Maximum number of images per API call (20 in this case)
    • Max size of each image (5 mb)

Happy to take this up.

Implement Delta for Stream

@madebywelch Thank you so much for implementing the streaming feature! I just tested it out and it works (<24 after I opened the initial issue ๐Ÿ”ฅ )!

One request I'd make is adding a Delta to the stream response which has the new chunk that is the "delta" of the last one. Here is how OpenAI implements it.

This feature will help with use cases where we're streaming in chunks from a backend to a frontend.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.