convez.ai
PluginIntegração & APIsIntermediário
dleviminzi

Anthrogo - Cliente Go para API Anthropic

dleviminzi/anthrogo

Cliente Go simples para chamar Claude via API Anthropic

Ver no GitHub
InicialPluginScore · de 0 a 100

Wrapper não-oficial para a API Anthropic em Go, facilitando a integração do Claude em aplicações Go. Suporta requisições síncronas, streaming SSE e a API legada de completions, com tipos estruturados e tratamento de erros.

Instalação

$npx convez-ai dleviminzi/anthrogo

1 comando no terminal: detecta o formato do repositório (marketplace ou plugin avulso) e instala via Claude Code. Requer Node 18+ e o Claude Code instalado.

Métricas

Estrelas
12
Forks
2
Acompanhando
1
Saúde
42%
Último commit
há 2 anos
Versão
v1.0.1
Issues abertas
0
Contribuidores
2

Casos de uso

  • Integrar Claude em backends Go
  • Criar bots e chatbots em Go com streaming
  • Construir pipelines de processamento com IA

Veredito

Biblioteca leve e pragmática para quem desenvolve em Go e precisa chamar Claude. Bem estruturada com exemplos claros, mas sendo não-oficial exige monitoramento de mudanças na API Anthropic e não garante paridade com novas features.

README

A tradução para o português deste README ainda está na fila.

anthropic go (anthrogo)

Go Reference Go Report Card codecov

This is a simple client for using Anthropic's api to get claude completions. It is not an official client. Contributions are welcome!

Installation

go get github.com/dleviminzi/anthrogo

Basic usage

Message API

func main() {
	c, err := anthrogo.NewClient()
	if err != nil {
		log.Fatal(err)
		os.Exit(1)
	}

	systemPrompt := "you are an expert in all things bananas"

	// Read user input for the prompt
	reader := bufio.NewReader(os.Stdin)
	fmt.Print("Enter your prompt: ")
	userPrompt, _ := reader.ReadString('\n')
	userPrompt = strings.TrimSuffix(userPrompt, "\n")

	resp, err := c.MessageRequest(context.Background(), anthrogo.MessagePayload{
		Model: anthrogo.ModelClaude3Opus,
		Messages: []anthrogo.Message{{
			Role: anthrogo.RoleTypeUser,
			Content: []anthrogo.MessageContent{{
				Type: anthrogo.ContentTypeText,
				Text: &userPrompt,
			}},
		}},
		System:    &systemPrompt,
		MaxTokens: 1000,
	})
	if err != nil {
		log.Fatal(err)
		os.Exit(1)
	}

	fmt.Println(resp.Content[0].Text)
}

Message Streaming

message-streaming-example

func main() {
	c, err := anthrogo.NewClient()
	if err != nil {
		log.Fatal(err)
		os.Exit(1)
	}
	
	systemPrompt := "you are an expert in all things bananas"
	
	// Read user input for the prompt
	reader := bufio.NewReader(os.Stdin)
	fmt.Print("Enter your prompt: ")
	userPrompt, _ := reader.ReadString('\n')
	userPrompt = strings.TrimSuffix(userPrompt, "\n")
	
	r, _, err := c.MessageStreamRequest(context.Background(), anthrogo.MessagePayload{
		Model: anthrogo.ModelClaude3Opus,
		Messages: []anthrogo.Message{{
			Role: anthrogo.RoleTypeUser,
			Content: []anthrogo.MessageContent{{
				Type: anthrogo.ContentTypeText,
				Text: &userPrompt,
			}},
		}},
		System:    &systemPrompt,
		MaxTokens: 1000,
	})
	if err != nil {
		log.Fatal(err)
		os.Exit(1)
	}
	defer r.Close()
	
	// Create an SSEDecoder
	decoder := anthrogo.NewMessageSSEDecoder(r)
	for {
		message, err := decoder.Decode(anthrogo.DecodeOptions{ContentOnly: true})
		if err != nil {
			if err == io.EOF {
				break
			}
			fmt.Print(err)
			continue
		}
	
		if message.Event == "message_stop" {
			break
		}
	
		fmt.Print(message.Data.Content)
	}
}

Completions (old api)

func main() {
	c, err := anthrogo.NewClient()
	if err != nil {
		log.Fatal(err)
		os.Exit(1)
	}

	// Read user input for the prompt
	reader := bufio.NewReader(os.Stdin)
	fmt.Print("Enter your prompt: ")
	userPrompt, _ := reader.ReadString('\n')
	userPrompt = strings.TrimSuffix(userPrompt, "\n")

	// Create conversation with user input
	conversation := anthrogo.NewConversation()
	conversation.AddMessage(anthrogo.RoleHuman, userPrompt)

	// Set up the payload and send completion stream request
	resp, err := c.CompletionRequest(context.Background(), anthrogo.CompletionPayload{
		MaxTokensToSample: 256,
		Model:             anthrogo.ModelClaude2,
		Prompt:            conversation.GeneratePrompt(),
	})
	if err != nil {
		log.Fatal(err)
		os.Exit(1)
	}

	fmt.Println(resp.Completion)

	// Add claude's response to conversation for further prompting...
	conversation.AddMessage(anthrogo.RoleAssistant, resp.Completion)
}

Completion Streaming

streaming-completion-example (trimmed).webm

func main() {
	// Create a new client
	// optionally provide api key otherwise we will look for it in ANTHROPIC_API_KEY variable
	c, err := anthrogo.NewClient()
	if err != nil {
		log.Fatal(err)
		os.Exit(1)
	}

	// Read user input for the prompt
	reader := bufio.NewReader(os.Stdin)
	fmt.Print("Enter your prompt: ")
	userPrompt, _ := reader.ReadString('\n')
	userPrompt = strings.TrimSuffix(userPrompt, "\n")

	// Create conversation with user input
	conversation := anthrogo.NewConversation()
	conversation.AddMessage(anthrogo.RoleHuman, userPrompt)

	// Set up the payload and send completion stream request
	completeStreamResp, _ := c.StreamingCompletionRequest(context.Background(), anthrogo.CompletionPayload{
		MaxTokensToSample: 256,
		Model:             anthrogo.ModelClaude2,
		Prompt:            conversation.GeneratePrompt(),
		CompleteOptions: anthrogo.CompleteOptions{
			Stream:      true,
			Temperature: 1,
		},
	})

	// Ensure that the request is canceled after timeout (default 1 minute)
	defer completeStreamResp.Cancel()

	// Ensure that the stream response body is closed when the function returns
	defer completeStreamResp.Close()

	// Continually read from the response until an error or EOF is encountered
	for {
		event, err := completeStreamResp.Decode()
		if err != nil {
			if err == io.EOF {
				break
			} else {
				fmt.Println(err)
				os.Exit(1)
			}
		}

		if event != nil {
			fmt.Printf("%s", event.Data.Completion)
		}
	}
}
Ver o original no GitHub

Bom para

Relacionados