View a markdown version of this page

Esempi per l’API Runtime per Amazon Bedrock con SDK per Go V2 - AWS Esempi di codice SDK

Sono disponibili altri esempi AWS SDK nel repository AWS Doc SDK Examples. GitHub

Le traduzioni sono generate tramite traduzione automatica. In caso di conflitto tra il contenuto di una traduzione e la versione originale in Inglese, quest'ultima prevarrà.

Esempi per l’API Runtime per Amazon Bedrock con SDK per Go V2

I seguenti esempi di codice mostrano come eseguire azioni e implementare scenari comuni utilizzando AWS SDK per Go V2 con Amazon Bedrock Runtime.

Ogni esempio include un link al codice sorgente completo, in cui vengono fornite le istruzioni su come configurare ed eseguire il codice nel contesto.

Nozioni di base

Il seguente esempio di codice mostra come iniziare a usare Amazon Bedrock Runtime.

SDK per Go V2
Nota

C'è altro su. GitHub Trova l'esempio completo e scopri di più sulla configurazione e l'esecuzione nel Repository di esempi di codice AWS.

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) }
  • Per informazioni dettagliate sull’API, consulta Converse nella documentazione di riferimento dell’API AWS SDK per Go .

Amazon Nova

L’esempio di codice seguente mostra come inviare un messaggio di testo ad Amazon Nova utilizzando l’API Converse di Bedrock.

SDK per Go V2
Nota

C'è dell'altro GitHub. Trova l'esempio completo e scopri di più sulla configurazione e l'esecuzione nel Repository di esempi di codice AWS.

Invia un messaggio di testo ad Amazon Nova utilizzando l’API Converse di 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 }
  • Per informazioni dettagliate sull’API, consulta Converse nella documentazione di riferimento dell’API AWS SDK per Go .

Generatore di immagini Amazon Titan

L’esempio di codice seguente mostra come invocare Generatore di immagini Amazon Titan in Amazon Bedrock per generare un’immagine.

SDK per Go V2
Nota

C'è dell'altro GitHub. Trova l'esempio completo e scopri di più sulla configurazione e l'esecuzione nel Repository di esempi di codice AWS.

Crea un’immagine con Generatore di immagini 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 }
  • Per i dettagli sull'API, consulta la InvokeModelsezione AWS SDK per Go API Reference.

Anthropic Claude

L’esempio di codice seguente mostra come inviare un messaggio di testo ad Anthropic Claude utilizzando l’API Converse di Bedrock.

SDK per Go V2
Nota

C'è di più su GitHub. Trova l'esempio completo e scopri di più sulla configurazione e l'esecuzione nel Repository di esempi di codice AWS.

Invia un messaggio di testo ad Anthropic Claude utilizzando l’API Converse di 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 }
  • Per informazioni dettagliate sull’API, consulta Converse nella documentazione di riferimento dell’API AWS SDK per Go .