View a markdown version of this page

Exemplos do Amazon Bedrock Runtime usando o SDK para Go V2 - AWS Exemplos de código do SDK

Há mais exemplos de AWS SDK disponíveis no repositório AWS Doc SDK Examples GitHub .

As traduções são geradas por tradução automática. Em caso de conflito entre o conteúdo da tradução e da versão original em inglês, a versão em inglês prevalecerá.

Exemplos do Amazon Bedrock Runtime usando o SDK para Go V2

Os exemplos de código a seguir mostram como realizar ações e implementar cenários comuns usando o AWS SDK para Go V2 com o Amazon Bedrock Runtime.

Cada exemplo inclui um link para o código-fonte completo, em que você pode encontrar instruções sobre como configurar e executar o código.

Conceitos básicos

O exemplo de código a seguir mostra como começar a usar o Amazon Bedrock Runtime.

SDK para Go V2
nota

Tem mais sobre GitHub. Encontre o exemplo completo e saiba como configurar e executar no AWS Code Examples Repository.

package main import ( "context" "flag" "fmt" "log" "github.com/aws/aws-sdk-go-v2/aws" "github.com/aws/aws-sdk-go-v2/config" "github.com/aws/aws-sdk-go-v2/service/bedrockruntime" "github.com/aws/aws-sdk-go-v2/service/bedrockruntime/types" ) // main uses the AWS SDK for Go (v2) to create an Amazon Bedrock Runtime client // and invokes Anthropic Claude using the Converse API. // This example uses the default settings specified in your shared credentials // and config files. func main() { region := flag.String("region", "us-east-1", "The AWS region") flag.Parse() fmt.Printf("Using AWS region: %s\n", *region) ctx := context.Background() sdkConfig, err := config.LoadDefaultConfig(ctx, config.WithRegion(*region)) if err != nil { fmt.Println("Couldn't load default configuration. Have you set up your AWS account?") fmt.Println(err) return } client := bedrockruntime.NewFromConfig(sdkConfig) // Set the model ID, e.g., Claude Haiku. // The "global." prefix enables cross-region inference, allowing the request // to be routed to the nearest available region for the specified model. modelId := "global.anthropic.claude-haiku-4-5-20251001-v1:0" // Start a conversation with the user message. prompt := "Hello. In a short paragraph, explain what you can do." message := types.Message{ Content: []types.ContentBlock{ &types.ContentBlockMemberText{Value: prompt}, }, Role: types.ConversationRoleUser, } fmt.Printf("Model: %s\n", modelId) fmt.Printf("Prompt: %s\n\n", prompt) result, err := client.Converse(ctx, &bedrockruntime.ConverseInput{ ModelId: aws.String(modelId), Messages: []types.Message{message}, }) if err != nil { log.Fatalf("ERROR: Can't invoke '%s'. Reason: %v\n", modelId, err) } // Extract and print the response text. responseMessage, ok := result.Output.(*types.ConverseOutputMemberMessage) if !ok { log.Fatal("ERROR: Unexpected output type from Converse API") } responseContentBlock := responseMessage.Value.Content[0] text, ok := responseContentBlock.(*types.ContentBlockMemberText) if !ok { log.Fatal("ERROR: Unexpected content block type from Converse API") } fmt.Printf("Response: %s\n", text.Value) }
  • Consulte detalhes da API em Converse na Referência de API do AWS SDK para Go .

Amazon Nova

O exemplo de código a seguir mostra como enviar uma mensagem de texto para o Amazon Nova usando a API Converse do Bedrock.

SDK para Go V2
nota

Tem mais sobre GitHub. Encontre o exemplo completo e saiba como configurar e executar no AWS Code Examples Repository.

Envie uma mensagem de texto para o Amazon Nova usando a API Converse do Bedrock.

func (wrapper ConverseWrapper) ConverseNova(ctx context.Context, prompt string) (string, error) { var content = types.ContentBlockMemberText{ Value: prompt, } var message = types.Message{ Content: []types.ContentBlock{&content}, Role: "user", } modelId := "amazon.nova-lite-v1:0" var converseInput = bedrockruntime.ConverseInput{ ModelId: aws.String(modelId), Messages: []types.Message{message}, } response, err := wrapper.BedrockRuntimeClient.Converse(ctx, &converseInput) if err != nil { ProcessError(err, modelId) } responseText, _ := response.Output.(*types.ConverseOutputMemberMessage) responseContentBlock := responseText.Value.Content[0] text, _ := responseContentBlock.(*types.ContentBlockMemberText) return text.Value, nil }
  • Consulte detalhes da API em Converse na Referência de API do AWS SDK para Go .

Gerador de Imagens do Amazon Titan

O exemplo de código a seguir mostra como invocar o Amazon Titan Image no Amazon Bedrock para gerar uma imagem.

SDK para Go V2
nota

Tem mais sobre GitHub. Encontre o exemplo completo e saiba como configurar e executar no AWS Code Examples Repository.

Crie uma imagem com o Gerador de Imagens do Amazon Titan.

import ( "context" "encoding/json" "log" "strings" "github.com/aws/aws-sdk-go-v2/aws" "github.com/aws/aws-sdk-go-v2/service/bedrockruntime" ) // InvokeModelWrapper encapsulates Amazon Bedrock actions used in the examples. // It contains a Bedrock Runtime client that is used to invoke foundation models. type InvokeModelWrapper struct { BedrockRuntimeClient *bedrockruntime.Client } type TitanImageRequest struct { TaskType string `json:"taskType"` TextToImageParams TextToImageParams `json:"textToImageParams"` ImageGenerationConfig ImageGenerationConfig `json:"imageGenerationConfig"` } type TextToImageParams struct { Text string `json:"text"` } type ImageGenerationConfig struct { NumberOfImages int `json:"numberOfImages"` Quality string `json:"quality"` CfgScale float64 `json:"cfgScale"` Height int `json:"height"` Width int `json:"width"` Seed int64 `json:"seed"` } type TitanImageResponse struct { Images []string `json:"images"` } // Invokes the Titan Image model to create an image using the input provided // in the request body. func (wrapper InvokeModelWrapper) InvokeTitanImage(ctx context.Context, prompt string, seed int64) (string, error) { modelId := "amazon.titan-image-generator-v2:0" body, err := json.Marshal(TitanImageRequest{ TaskType: "TEXT_IMAGE", TextToImageParams: TextToImageParams{ Text: prompt, }, ImageGenerationConfig: ImageGenerationConfig{ NumberOfImages: 1, Quality: "standard", CfgScale: 8.0, Height: 512, Width: 512, Seed: seed, }, }) if err != nil { log.Fatal("failed to marshal", err) } output, err := wrapper.BedrockRuntimeClient.InvokeModel(ctx, &bedrockruntime.InvokeModelInput{ ModelId: aws.String(modelId), ContentType: aws.String("application/json"), Body: body, }) if err != nil { ProcessError(err, modelId) } var response TitanImageResponse if err := json.Unmarshal(output.Body, &response); err != nil { log.Fatal("failed to unmarshal", err) } base64ImageData := response.Images[0] return base64ImageData, nil }
  • Para obter detalhes da API, consulte InvokeModela Referência AWS SDK para Go da API.

Claude da Anthropic

O exemplo de código a seguir mostra como enviar uma mensagem de texto ao Claude da Anthropic usando a API Converse do Bedrock.

SDK para Go V2
nota

Tem mais sobre GitHub. Encontre o exemplo completo e saiba como configurar e executar no AWS Code Examples Repository.

Envie uma mensagem de texto ao Claude da Anthropic usando a API Converse do Bedrock.

import ( "context" "github.com/aws/aws-sdk-go-v2/aws" "github.com/aws/aws-sdk-go-v2/service/bedrockruntime" "github.com/aws/aws-sdk-go-v2/service/bedrockruntime/types" ) // ConverseWrapper encapsulates Amazon Bedrock actions used in the examples. // It contains a Bedrock Runtime client that is used to invoke Bedrock. type ConverseWrapper struct { BedrockRuntimeClient *bedrockruntime.Client } func (wrapper ConverseWrapper) ConverseClaude(ctx context.Context, prompt string) (string, error) { var content = types.ContentBlockMemberText{ Value: prompt, } var message = types.Message{ Content: []types.ContentBlock{&content}, Role: "user", } modelId := "anthropic.claude-3-haiku-20240307-v1:0" var converseInput = bedrockruntime.ConverseInput{ ModelId: aws.String(modelId), Messages: []types.Message{message}, } response, err := wrapper.BedrockRuntimeClient.Converse(ctx, &converseInput) if err != nil { ProcessError(err, modelId) } responseText, _ := response.Output.(*types.ConverseOutputMemberMessage) responseContentBlock := responseText.Value.Content[0] text, _ := responseContentBlock.(*types.ContentBlockMemberText) return text.Value, nil }
  • Consulte detalhes da API em Converse na Referência de API do AWS SDK para Go .