forked from awsdocs/aws-doc-sdk-examples
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathinvoke_model.go
More file actions
169 lines (135 loc) · 5.1 KB
/
invoke_model.go
File metadata and controls
169 lines (135 loc) · 5.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package actions
// snippet-start:[gov2.bedrock-runtime.InvokeModelWrapper.complete]
// snippet-start:[gov2.bedrock-runtime.InvokeModelWrapper.struct]
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
}
// snippet-end:[gov2.bedrock-runtime.InvokeModelWrapper.struct]
// snippet-start:[gov2.bedrock-runtime.InvokeClaude]
// Each model provider has their own individual request and response formats.
// For the format, ranges, and default values for Anthropic Claude, refer to:
// https://docs.aws.amazon.com/bedrock/latest/userguide/model-parameters-claude.html
type ClaudeRequest struct {
Prompt string `json:"prompt"`
MaxTokensToSample int `json:"max_tokens_to_sample"`
Temperature float64 `json:"temperature,omitempty"`
StopSequences []string `json:"stop_sequences,omitempty"`
}
type ClaudeResponse struct {
Completion string `json:"completion"`
}
// Invokes Anthropic Claude on Amazon Bedrock to run an inference using the input
// provided in the request body.
func (wrapper InvokeModelWrapper) InvokeClaude(ctx context.Context, prompt string) (string, error) {
modelId := "anthropic.claude-v2"
// Anthropic Claude requires enclosing the prompt as follows:
enclosedPrompt := "Human: " + prompt + "\n\nAssistant:"
body, err := json.Marshal(ClaudeRequest{
Prompt: enclosedPrompt,
MaxTokensToSample: 200,
Temperature: 0.5,
StopSequences: []string{"\n\nHuman:"},
})
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 ClaudeResponse
if err := json.Unmarshal(output.Body, &response); err != nil {
log.Fatal("failed to unmarshal", err)
}
return response.Completion, nil
}
// snippet-end:[gov2.bedrock-runtime.InvokeClaude]
// snippet-start:[gov2.bedrock-runtime.InvokeTitanImage]
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
}
// snippet-end:[gov2.bedrock-runtime.InvokeTitanImage]
func ProcessError(err error, modelId string) {
errMsg := err.Error()
if strings.Contains(errMsg, "no such host") {
log.Printf(`The Bedrock service is not available in the selected region.
Please double-check the service availability for your region at
https://aws.amazon.com/about-aws/global-infrastructure/regional-product-services/.\n`)
} else if strings.Contains(errMsg, "Could not resolve the foundation model") {
log.Printf(`Could not resolve the foundation model from model identifier: \"%v\".
Please verify that the requested model exists and is accessible
within the specified region.\n
`, modelId)
} else {
log.Printf("Couldn't invoke model: \"%v\". Here's why: %v\n", modelId, err)
}
}
// snippet-end:[gov2.bedrock-runtime.InvokeModelWrapper.complete]